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

include 'connection.php';
require 'vendor/autoload.php'; // Load Composer dependencies

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

$secret_key = "1ED495A77B65435D317B3E6582E4C"; 
$issuer = "http://kaninfotech.in"; 
$audience = "http://xesstechlink.com"; 

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

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

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

        // Get action type (add / edit / delete)
        $action = isset($_POST['action']) ? $_POST['action'] : '';

        if ($action === 'add') {
            if (!empty($_POST['main_area'])) {
                $main_area = $_POST['main_area'];

                // Check duplicate
                $checkQuery = "SELECT COUNT(*) as count FROM area WHERE main_area = ? AND com_id = ?";
                $checkStmt = $conn->prepare($checkQuery);
                $checkStmt->bind_param("si", $main_area, $company_id);
                $checkStmt->execute();
                $checkResult = $checkStmt->get_result();
                $checkRow = $checkResult->fetch_assoc();
                $checkStmt->close();

                if ($checkRow['count'] > 0) {
                    echo json_encode(["success" => false, "message" => "Area already exists!"]);
                    exit;
                }

                $stmt = $conn->prepare("INSERT INTO area (main_area, com_id) VALUES (?, ?)");
                $stmt->bind_param("si", $main_area, $company_id);

                if ($stmt->execute()) {
                    echo json_encode(["success" => true, "message" => "Area inserted successfully"]);
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to insert area: " . $stmt->error]);
                }
                $stmt->close();
            } else {
                echo json_encode(["success" => false, "message" => "main_area is required"]);
            }
        }

        elseif ($action === 'edit') {
            if (!empty($_POST['id']) && !empty($_POST['main_area'])) {
                $id = intval($_POST['id']);
                $main_area = $_POST['main_area'];

                $stmt = $conn->prepare("UPDATE area SET main_area = ? WHERE id = ? AND com_id = ?");
                $stmt->bind_param("sii", $main_area, $id, $company_id);

                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) {
                        echo json_encode(["success" => true, "message" => "Area updated successfully"]);
                    } else {
                        echo json_encode(["success" => false, "message" => "No matching record found or no changes made"]);
                    }
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to update area: " . $stmt->error]);
                }
                $stmt->close();
            } else {
                echo json_encode(["success" => false, "message" => "id and main_area are required"]);
            }
        }

        elseif ($action === 'delete') {
            if (!empty($_POST['id'])) {
                $id = intval($_POST['id']);

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

                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) {
                        echo json_encode(["success" => true, "message" => "Area deleted successfully"]);
                    } else {
                        echo json_encode(["success" => false, "message" => "No matching record found"]);
                    }
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to delete area: " . $stmt->error]);
                }
                $stmt->close();
            } else {
                echo json_encode(["success" => false, "message" => "id is required"]);
            }
        }

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

    } catch (ExpiredException $e) {
        echo json_encode(["success" => false, "message" => "Token has expired"]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Failed to decode token: " . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
