<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');

include 'connection.php';
require 'vendor/autoload.php'; // JWT library

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;
use \Firebase\JWT\ExpiredException;

$secret_key = "1ED495A77B65435D317B3E6582E4C";

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');
} else {
    echo json_encode(["success" => false, "message" => "Authorization header missing"]);
    exit;
}

try {
    $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
    $company_id = $decoded->data->companyId;
    $uid = $decoded->data->uid;

    // ✅ POST: Insert new agent
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents("php://input"), true);

        $name = trim($data['name'] ?? '');
        $mobile = trim($data['mobile_no'] ?? '');
        $address = trim($data['address'] ?? null);
        $aadhaar = trim($data['adhar_no'] ?? null);
        $loginTime = trim($data['login'] ?? null);
        $logoutTime = trim($data['logout'] ?? null);
        $status = trim($data['status'] ?? 'active');
        $line = trim($data['line'] ?? '');

        if (!$name || !$mobile || !$line || !$status) {
            echo json_encode(["success" => false, "message" => "Required fields missing"]);
            exit;
        }

        $stmt = $conn->prepare("INSERT INTO collection_agent
            (com_id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param(
            "issssssss",
            $company_id,
            $name,
            $mobile,
            $address,
            $aadhaar,
            $loginTime,
            $logoutTime,
            $status,
            $line
        );

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Collection Agent inserted successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Insert failed: " . $stmt->error]);
        }

        $stmt->close();
    } 

    // ✅ GET: Fetch all agents for this company
    elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $stmt = $conn->prepare("SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
                                FROM collection_agent 
                                WHERE com_id = ?");
        $stmt->bind_param("i", $company_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $agents = [];
        while ($row = $result->fetch_assoc()) {
            $agents[] = $row;
        }

        echo json_encode(["success" => true, "data" => $agents]);

        $stmt->close();
    }

    // ✅ PUT: Update agent by ID
    elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
        $data = json_decode(file_get_contents("php://input"), true);

        $id = $data['id'] ?? 0;
        $name = trim($data['name'] ?? '');
        $mobile = trim($data['mobile_no'] ?? '');
        $address = trim($data['address'] ?? null);
        $aadhaar = trim($data['adhar_no'] ?? null);
        $loginTime = trim($data['login'] ?? null);
        $logoutTime = trim($data['logout'] ?? null);
        $status = trim($data['status'] ?? 'active');
        $line = trim($data['line'] ?? '');

        if (!$id || !$name || !$mobile || !$line || !$status) {
            echo json_encode(["success" => false, "message" => "Required fields missing"]);
            exit;
        }

        $stmt = $conn->prepare("UPDATE collection_agent 
                                SET name=?, mobile_no=?, address=?, aadhar_no=?, report_in=?, reporting_time=?, status=?, line=? 
                                WHERE id=? AND com_id=?");
        $stmt->bind_param(
            "ssssssssii",
            $name,
            $mobile,
            $address,
            $aadhaar,
            $loginTime,
            $logoutTime,
            $status,
            $line,
            $id,
            $company_id
        );

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Collection Agent updated successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Update failed: " . $stmt->error]);
        }

        $stmt->close();
    }

    // ✅ DELETE: Delete agent by ID
    elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['id'] ?? 0;

        if (!$id) {
            echo json_encode(["success" => false, "message" => "Agent ID required"]);
            exit;
        }

        $stmt = $conn->prepare("DELETE FROM collection_agent WHERE id=? AND com_id=?");
        $stmt->bind_param("ii", $id, $company_id);

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Collection Agent deleted successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Delete failed: " . $stmt->error]);
        }

        $stmt->close();
    }

    else {
        echo json_encode(["success" => false, "message" => "Invalid request method"]);
    }

} catch (ExpiredException $e) {
    echo json_encode(["success" => false, "message" => "Token expired"]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "JWT decode failed: " . $e->getMessage()]);
}

$conn->close();
?>
