<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('repair_management');

$pdo = getDB();
$user = currentUser();
$user_id = $user['id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'], $_POST['job_id'])) {
    $_SESSION['error'] = 'Invalid request.';
    header('Location: repair_jobs.php'); exit;
}

$action = $_POST['action'];
$job_id = (int)$_POST['job_id'];

$stmt = $pdo->prepare("SELECT * FROM repair_jobs WHERE id = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch();
if (!$job) { $_SESSION['error'] = 'Job not found.'; header('Location: repair_jobs.php'); exit; }

$is_admin = in_array($user['role_name'], ['Super Admin', 'Admin']);

try {
    $pdo->beginTransaction();

    if ($action === 'mark_completed') {
        if (in_array($job['repair_status'], ['Delivered', 'Cancelled', 'Cannot Repair'])) {
            throw new Exception("Cannot mark a {$job['repair_status']} job as Completed.");
        }

        if ($job['final_amount'] == 0 && !$is_admin) {
            throw new Exception("Cannot mark as Completed when final amount is 0. Contact Super Admin.");
        }

        $old_status = $job['repair_status'];
        $pdo->prepare("UPDATE repair_jobs SET repair_status = 'Completed', updated_at = NOW() WHERE id = ?")->execute([$job_id]);
        $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, old_status, new_status, note, changed_by) VALUES (?,?,?,?,?)")
            ->execute([$job_id, $old_status, 'Completed', 'Job completed', $user_id]);
        logActivity('Marked Repair Completed', 'Repairs', $job_id);
        $_SESSION['success'] = 'Job marked as Completed. You can now deliver to customer.';

    } elseif ($action === 'mark_delivered') {
        if ($job['repair_status'] !== 'Completed') {
            throw new Exception('Job must be Completed before delivery.');
        }

        if ($job['due_amount'] > 0 && !$is_admin) {
            throw new Exception("Cannot deliver with outstanding balance of " . formatCurrency($job['due_amount']) . ". Contact Admin.");
        }

        $old_status = $job['repair_status'];
        $delivered_date = date('Y-m-d H:i:s');

        $pdo->prepare("UPDATE repair_jobs SET repair_status = 'Delivered', delivered_date = ?, updated_at = NOW() WHERE id = ?")
            ->execute([$delivered_date, $job_id]);

        $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, old_status, new_status, note, changed_by) VALUES (?,?,?,?,?)")
            ->execute([$job_id, $old_status, 'Delivered', 'Device delivered to customer', $user_id]);

        // Start repair warranty if warranty days > 0
        if ($job['repair_warranty_days'] > 0) {
            $warranty_start = date('Y-m-d');
            $warranty_end = date('Y-m-d', strtotime("+{$job['repair_warranty_days']} days"));

            $pdo->prepare("UPDATE repair_jobs SET repair_warranty_start_date = ?, repair_warranty_end_date = ? WHERE id = ?")
                ->execute([$warranty_start, $warranty_end, $job_id]);

            $pdo->prepare("INSERT INTO warranty_records (warranty_type, reference_type, reference_id, customer_id, product_id, warranty_start_date, warranty_end_date, warranty_status) VALUES ('repair', 'repair_job', ?, ?, NULL, ?, ?, 'Active')")
                ->execute([$job_id, $job['customer_id'], $warranty_start, $warranty_end]);
        }

        logActivity('Marked Repair Delivered', 'Repairs', $job_id);
        $_SESSION['success'] = 'Device delivered successfully. ' . ($job['repair_warranty_days'] > 0 ? "Warranty started ({$job['repair_warranty_days']} days)." : '');

    } elseif ($action === 'update_labour') {
        if ($job['repair_status'] === 'Delivered') {
            throw new Exception('Cannot update labour charge on delivered job.');
        }
        $labour_charge = (float)($_POST['labour_charge'] ?? 0);
        $pdo->prepare("UPDATE repair_jobs SET labour_charge = ?, final_amount = parts_total + ? - discount_amount, updated_at = NOW() WHERE id = ?")
            ->execute([$labour_charge, $labour_charge, $job_id]);
        $_SESSION['success'] = 'Labour charge updated.';

    } elseif ($action === 'update_discount') {
        if ($job['repair_status'] === 'Delivered') {
            throw new Exception('Cannot update discount on delivered job.');
        }
        $discount = (float)($_POST['discount_amount'] ?? 0);
        if ($discount < 0) $discount = 0;
        $pdo->prepare("UPDATE repair_jobs SET discount_amount = ?, final_amount = parts_total + labour_charge - ?, updated_at = NOW() WHERE id = ?")
            ->execute([$discount, $discount, $job_id]);
        $_SESSION['success'] = 'Discount updated.';
    } else {
        throw new Exception('Unknown action.');
    }

    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    $_SESSION['error'] = 'Error: ' . $e->getMessage();
}

header("Location: view_repair_job.php?id=$job_id");
exit;
