<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/auth.php';
requirePermission('view_network_jobs');

$BASE = app_base_path();

$user_id = $_SESSION['user_id'] ?? 0;
if (!$user_id) {
    redirect_to($BASE . '/login.php');
    exit;
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    redirect_to($BASE . '/installer/network/my_jobs.php');
    exit;
}

/* ===============================
   FETCH JOB
=================================*/
$stmt = $pdo->prepare("
    SELECT *
    FROM network_jobs
    WHERE id = ? AND assigned_installer_id = ?
    LIMIT 1
");
$stmt->execute([$id, $user_id]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$job) {
    http_response_code(404);
    die("Job not found or not assigned to you.");
}

$currentStatus = $job['status'];
$error = null;

/* ===============================
   START JOB
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_job']) && $currentStatus === 'ASSIGNED') {

    $pdo->prepare("
        UPDATE network_jobs
        SET status = 'IN_PROGRESS', updated_at = NOW()
        WHERE id = ? AND assigned_installer_id = ?
    ")->execute([$id, $user_id]);

    redirect_to($BASE . "/installer/network/view.php?id=" . $id);
    exit;
}

/* ===============================
   COMPLETE JOB (SECURE VERSION)
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_job']) && $currentStatus === 'IN_PROGRESS') {

    $notes = trim($_POST['completion_notes'] ?? '');
    $phone = trim($_POST['installer_phone'] ?? '');

    if ($notes === '') {
        $error = "Completion notes are required.";
    }

    if (!preg_match('/^[0-9]{10}$/', $phone)) {
        $error = "Phone number must be exactly 10 digits.";
    }

    if (!isset($_FILES['completion_photo']) || $_FILES['completion_photo']['error'] !== UPLOAD_ERR_OK) {
        $error = "Completion photo is required.";
    }

    if (!$error) {

        $file = $_FILES['completion_photo'];

        // Max file size 5MB
        if ($file['size'] > 5 * 1024 * 1024) {
            $error = "File size must not exceed 5MB.";
        }

        // Validate MIME type using finfo (secure)
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);

        $allowedMime = [
            'image/jpeg' => 'jpg',
            'image/png'  => 'png'
        ];

        if (!array_key_exists($mimeType, $allowedMime)) {
            $error = "Only JPG and PNG images are allowed.";
        }

        if (!$error) {

            $extension = $allowedMime[$mimeType];
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/completions/';

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            // Randomized filename (prevents overwrite & guessing)
            $fileName = 'job_' . $id . '_' . bin2hex(random_bytes(8)) . '.' . $extension;
            $targetPath = $uploadDir . $fileName;

            if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
                $error = "File upload failed.";
            } else {

                $dbPath = '/uploads/completions/' . $fileName;

                $pdo->prepare("
                    UPDATE network_jobs
                    SET status = 'COMPLETION_PENDING',
                        completion_notes = ?,
                        completion_photo = ?,
                        installer_phone = ?,
                        completed_at = NOW(),
                        updated_at = NOW()
                    WHERE id = ? AND assigned_installer_id = ?
                ")->execute([$notes, $dbPath, $phone, $id, $user_id]);

                redirect_to($BASE . "/installer/network/view.php?id=" . $id);
                exit;
            }
        }
    }
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">
    <h2>Job #<?= (int)$job['id'] ?> — <?= htmlspecialchars($job['title']) ?></h2>
    <p class="page-subtitle">Installer Workflow</p>
</div>

<?php if ($error): ?>
    <div class="alert-error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<div class="card">

<h4>Location</h4>
<p>
<?= htmlspecialchars($job['street_address']) ?><br>
<?= htmlspecialchars($job['suburb']) ?>,
<?= htmlspecialchars($job['city']) ?>,
<?= htmlspecialchars($job['province']) ?>
</p>

<hr>

<h4>Description</h4>
<p><?= nl2br(htmlspecialchars($job['description'])) ?></p>

<hr>

<h4>Status</h4>
<p><strong>Current:</strong> <?= htmlspecialchars($job['status']) ?></p>

<br>

<?php if ($currentStatus === 'ASSIGNED'): ?>

    <form method="POST">
        <button class="btn-primary" name="start_job">
            Start Job (Move to IN_PROGRESS)
        </button>
    </form>

<?php elseif ($currentStatus === 'IN_PROGRESS'): ?>

    <h4>Submit Completion (Proof Required)</h4>

    <form method="POST" enctype="multipart/form-data">

        <textarea name="completion_notes"
                  required
                  placeholder="Enter completion notes..."
                  style="width:100%;padding:10px;border-radius:8px;margin-bottom:15px;"></textarea>

        <input type="text"
               name="installer_phone"
               required
               maxlength="10"
               pattern="[0-9]{10}"
               placeholder="Installer Phone (10 digits)"
               style="width:100%;padding:10px;border-radius:8px;margin-bottom:15px;">

        <input type="file"
               name="completion_photo"
               accept="image/jpeg,image/png"
               required
               style="margin-bottom:15px;">

        <button class="btn-primary" name="complete_job">
            Submit for OPS Verification
        </button>

    </form>

<?php elseif ($currentStatus === 'COMPLETION_PENDING'): ?>

    <p style="color:orange;">
        <strong>Waiting for OPS verification...</strong>
    </p>

<?php elseif ($currentStatus === 'CLOSED'): ?>

    <p style="color:green;">
        <strong>Job Verified & Closed.</strong>
    </p>

<?php endif; ?>

<br>
<a class="btn-secondary" href="<?= $BASE ?>/installer/network/my_jobs.php">Back</a>

</div>
</div>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/footer.php'; ?>