<?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"; 

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

// Get JWT token from headers
$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 {
    $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
    $company_id = $decoded->data->companyId;
    $uid = $decoded->data->uid;

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

        if (!empty($data['line_name']) && !empty($data['areas']) && is_array($data['areas'])) {
            $line_name = trim($data['line_name']);
            $areas = $data['areas'];

            $conn->begin_transaction();
            $stmt = $conn->prepare("INSERT INTO line_entry (line, area, com_id) VALUES (?, ?, ?)");
            foreach ($areas as $area) {
                $stmt->bind_param("ssi", $line_name, $area, $company_id);
                if (!$stmt->execute()) {
                    $conn->rollback();
                    echo json_encode(["success" => false, "message" => "Failed to insert line-area: " . $stmt->error]);
                    exit;
                }
            }
            $stmt->close();
            $conn->commit();

            echo json_encode(["success" => true, "message" => "Line and Areas inserted successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Required fields missing or invalid"]);
        }

    } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Fetch distinct lines for the company
        $query = "SELECT DISTINCT line FROM line_entry WHERE com_id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $company_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $lines = [];
        while ($row = $result->fetch_assoc()) {
            $lines[] = $row['line'];
        }

        $stmt->close();
        echo json_encode(["success" => true, "data" => $lines]);

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

} 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()]);
}

$conn->close();
?>
