<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AttendanceApi extends CI_Controller
{
    public function push()
    {
        // If accessed via browser/GET just show a simple message
        if ($this->input->method() === 'get') {
            echo json_encode(['message' => 'Attendance API is running']);
            return;
        }

        // Receive raw JSON
        $rawInput = file_get_contents('php://input');
        $input = json_decode($rawInput, true);

        // Optional: validate API key
        // $apiKey = $this->input->get_request_header('X-API-Key');
        // if ($apiKey !== 'your-secret-key') { show_error('Invalid API key', 401); }

        if (empty($input) || !isset($input['records'])) {
            // 400 Bad Request
            $this->output
                ->set_status_header(400)
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'message' => 'No data received']));
            return;
        }

        // Save each record to DB
        foreach ($input['records'] as $record) {
            $data = [
                'user_id'   => $record['user_id'],
                'timestamp' => $record['timestamp'],
                'device_id' => $record['device_id'],
                'status'    => $record['status']
            ];
            $this->db->insert('attendance_logs', $data);
        }

        // Respond success
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['status' => 'ok']));
    }
}
