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

require_once __DIR__ . '/../../../includes/auth.php';
requirePermission('manage_network_jobs');

$BASE = app_base_path();

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id <= 0) {
    header("Location: " . $BASE . "/operations/network/index.php");
    exit;
}

/* ======================================================
   ISO AUDIT LOG HELPER (C)
====================================================== */
function audit_log(PDO $pdo, int $jobId, string $action, string $details = ''): void
{
    $userId = $_SESSION['user_id'] ?? null;
    $ip     = $_SERVER['REMOTE_ADDR'] ?? null;

    try {
        $stmt = $pdo->prepare("
            INSERT INTO network_job_audit
            (job_id, action, details, performed_by, ip_address, performed_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$jobId, $action, $details, $userId, $ip]);
    } catch (Exception $e) {
        // Do not break core flow if audit table not yet created
        // (safe fallback during rollout)
    }
}

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

if (!$job) {
    die("Job not found.");
}

/* ===============================
   HANDLE POST ACTIONS
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* ======================================================
       A + B: OPS COMPLETION VERIFICATION (Approve/Reject)
       - Works when Installer submits completion and job becomes COMPLETION_PENDING
       - Approve => VERIFIED then AUTO-CLOSE
       - Reject => back to IN_PROGRESS and capture rejection reason
    ====================================================== */

    // APPROVE COMPLETION (A)
    if (isset($_POST['approve_completion'])) {

        $pdo->beginTransaction();

        // VERIFIED -> CLOSED (auto close after approval)
        $upd = $pdo->prepare("
            UPDATE network_jobs
            SET status = 'CLOSED',
                verified_at = NOW(),
                verified_by = ?
            WHERE id = ?
        ");
        $upd->execute([($_SESSION['user_id'] ?? null), $id]);

        audit_log($pdo, $id, 'COMPLETION_APPROVED', 'OPS approved completion. Auto-closed job.');

        $pdo->commit();

        header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
        exit;
    }

    // REJECT COMPLETION (B)
    if (isset($_POST['reject_completion'])) {

        $reason = trim($_POST['rejection_reason'] ?? '');

        if ($reason === '') {
            // simple server-side validation
            header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
            exit;
        }

        $pdo->beginTransaction();

        $upd = $pdo->prepare("
            UPDATE network_jobs
            SET status = 'IN_PROGRESS',
                completion_rejection_reason = ?,
                completion_rejected_at = NOW(),
                completion_rejected_by = ?
            WHERE id = ?
        ");
        $upd->execute([$reason, ($_SESSION['user_id'] ?? null), $id]);

        audit_log($pdo, $id, 'COMPLETION_REJECTED', 'Reason: ' . $reason);

        $pdo->commit();

        header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
        exit;
    }

    /* ===============================
       ACCEPT QUOTE
    =================================*/
    if (isset($_POST['accept_quote_id'])) {

        $acceptQuoteId = (int)$_POST['accept_quote_id'];

        $pdo->beginTransaction();

        // Get installer for selected quote
        $stmt = $pdo->prepare("
            SELECT installer_user_id
            FROM network_job_quotes
            WHERE id = ? AND job_id = ?
        ");
        $stmt->execute([$acceptQuoteId, $id]);
        $acceptedQuote = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($acceptedQuote) {

            $installerId = $acceptedQuote['installer_user_id'];

            // Accept selected quote
            $pdo->prepare("
                UPDATE network_job_quotes
                SET status = 'ACCEPTED'
                WHERE id = ?
            ")->execute([$acceptQuoteId]);

            // Reject other quotes
            $pdo->prepare("
                UPDATE network_job_quotes
                SET status = 'REJECTED'
                WHERE job_id = ? AND id != ?
            ")->execute([$id, $acceptQuoteId]);

            // Mark selected invite as accepted
            $pdo->prepare("
                UPDATE network_job_invites
                SET status = 'ACCEPTED'
                WHERE job_id = ? AND installer_user_id = ?
            ")->execute([$id, $installerId]);

            // Close other invites
            $pdo->prepare("
                UPDATE network_job_invites
                SET status = 'CLOSED'
                WHERE job_id = ? AND installer_user_id != ?
            ")->execute([$id, $installerId]);

            $pdo->prepare("
                UPDATE network_jobs
                SET status = 'ASSIGNED',
                    assigned_installer_id = ?
                WHERE id = ?
            ")->execute([$installerId, $id]);

            audit_log($pdo, $id, 'QUOTE_ACCEPTED', 'Accepted quote_id=' . $acceptQuoteId . ', installer_id=' . $installerId);

            $pdo->commit();
        }

        header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
        exit;
    }

    /* ===============================
       UPDATE JOB STATUS
    =================================*/
    if (isset($_POST['update_job'])) {

        $newStatus = $_POST['status'] ?? $job['status'];
        $depositRequired = $_POST['deposit_required'] ?? $job['deposit_required'];

        $update = $pdo->prepare("
            UPDATE network_jobs
            SET status = ?, deposit_required = ?
            WHERE id = ?
        ");
        $update->execute([$newStatus, $depositRequired, $id]);

        audit_log($pdo, $id, 'STATUS_UPDATED', 'OPS set status=' . $newStatus . ', deposit_required=' . $depositRequired);

        header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
        exit;
    }

    /* ===============================
       SEND INVITES
    =================================*/
    if (isset($_POST['send_invites'])) {

        $selectedInstallers = $_POST['installer_ids'] ?? [];
        $expiresAt = $_POST['expires_at'] ?? '';

        if (!empty($expiresAt)) {
            $expiresAt = str_replace('T', ' ', $expiresAt) . ':00';
        } else {
            $expiresAt = date('Y-m-d H:i:s', strtotime('+48 hours'));
        }

        if (!empty($selectedInstallers)) {

            $pdo->beginTransaction();

            $insert = $pdo->prepare("
                INSERT INTO network_job_invites
                (job_id, installer_user_id, status, expires_at)
                VALUES (?, ?, 'INVITED', ?)
            ");

            $check = $pdo->prepare("
                SELECT COUNT(*)
                FROM network_job_invites
                WHERE job_id = ? AND installer_user_id = ?
            ");

            $sentCount = 0;

            foreach ($selectedInstallers as $installerId) {

                $installerId = (int)$installerId;

                $check->execute([$id, $installerId]);

                if ((int)$check->fetchColumn() === 0) {
                    $insert->execute([$id, $installerId, $expiresAt]);
                    $sentCount++;
                }
            }

            $pdo->prepare("
                UPDATE network_jobs
                SET status = 'INVITED_FOR_QUOTE'
                WHERE id = ?
            ")->execute([$id]);

            audit_log($pdo, $id, 'INVITES_SENT', 'Invites sent=' . $sentCount . ', expires_at=' . $expiresAt);

            $pdo->commit();
        }

        header("Location: " . $BASE . "/operations/network/view.php?id=" . $id);
        exit;
    }
}

/* ===============================
   FETCH INSTALLERS
=================================*/
$installersStmt = $pdo->query("
    SELECT u.id, u.full_name, ip.trade, ip.base_city, ip.base_suburb
    FROM users u
    JOIN installer_profiles ip ON ip.user_id = u.id
    WHERE u.status = 'ACTIVE'
      AND ip.is_active = 1
    ORDER BY u.full_name ASC
");
$installers = $installersStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   FETCH EXISTING INVITES
=================================*/
$invStmt = $pdo->prepare("
    SELECT i.installer_user_id, i.status, i.expires_at, u.full_name
    FROM network_job_invites i
    JOIN users u ON u.id = i.installer_user_id
    WHERE i.job_id = ?
    ORDER BY i.invited_at DESC
");
$invStmt->execute([$id]);
$existingInvites = $invStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   FETCH QUOTES
=================================*/
$quotesStmt = $pdo->prepare("
    SELECT q.*, u.full_name
    FROM network_job_quotes q
    JOIN users u ON u.id = q.installer_user_id
    WHERE q.job_id = ?
    ORDER BY q.submitted_at DESC
");
$quotesStmt->execute([$id]);
$quotes = $quotesStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   FETCH AUDIT LOG (C)
=================================*/
$auditRows = [];
try {
    $aStmt = $pdo->prepare("
        SELECT a.*, u.full_name
        FROM network_job_audit a
        LEFT JOIN users u ON u.id = a.performed_by
        WHERE a.job_id = ?
        ORDER BY a.performed_at DESC
        LIMIT 50
    ");
    $aStmt->execute([$id]);
    $auditRows = $aStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $auditRows = [];
}

require_once __DIR__ . '/../../../includes/header.php';
require_once __DIR__ . '/../../../includes/sidebar.php';
?>

<div class="main-content">

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

<div class="card">

<h4>Client Information</h4>
<p><strong>Name:</strong> <?= htmlspecialchars($job['client_name']) ?></p>
<p><strong>Email:</strong> <?= htmlspecialchars($job['client_email']) ?></p>
<p><strong>Phone:</strong> <?= htmlspecialchars($job['client_phone']) ?></p>

<hr>

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

<hr>

<h4>Job Details</h4>
<p><strong>Category:</strong> <?= htmlspecialchars($job['category']) ?></p>
<p><?= nl2br(htmlspecialchars($job['description'])) ?></p>

<hr>

<!-- ======================================================
     A + B: COMPLETION VERIFICATION PANEL (OPS)
====================================================== -->
<?php if (($job['status'] ?? '') === 'COMPLETION_PENDING'): ?>
    <h4>Completion Verification (OPS)</h4>

    <div class="card" style="border:1px solid #eee;padding:15px;border-radius:12px;background:#fafafa;">
        <p><strong>Installer Phone:</strong> <?= htmlspecialchars($job['installer_phone'] ?? '') ?></p>
        <p><strong>Completion Notes:</strong><br><?= nl2br(htmlspecialchars($job['completion_notes'] ?? '')) ?></p>

        <?php if (!empty($job['completion_photo'])): ?>
            <p><strong>Completion Photo:</strong></p>
            <a href="<?= htmlspecialchars($job['completion_photo']) ?>" target="_blank">View Photo</a>
        <?php else: ?>
            <p><strong>Completion Photo:</strong> Not provided</p>
        <?php endif; ?>

        <hr>

        <form method="POST" style="display:flex;gap:10px;flex-wrap:wrap;">
            <button type="submit" name="approve_completion" class="btn-primary">
                Approve & Close
            </button>
        </form>

        <br>

        <form method="POST">
            <label><strong>Reject Reason (Required)</strong></label>
            <textarea name="rejection_reason" class="form-control" required
                style="min-height:90px;margin-top:6px;"
                placeholder="Explain why completion is rejected (e.g. wrong meter installed / photo unclear / work incomplete)."></textarea>
            <br>
            <button type="submit" name="reject_completion" class="btn-danger">
                Reject Completion (Send Back)
            </button>
        </form>
    </div>

    <hr>
<?php endif; ?>

<?php if (!empty($job['completion_rejection_reason'])): ?>
    <div class="alert-error" style="margin-bottom:15px;">
        <strong>Last Rejection Reason:</strong><br>
        <?= nl2br(htmlspecialchars($job['completion_rejection_reason'])) ?>
    </div>
<?php endif; ?>

<h4>Status Control</h4>

<form method="POST">
<select name="status" class="form-control">
<?php
$statuses = [
'SUBMITTED','REVIEWING','QUOTED_TO_CLIENT','DEPOSIT_REQUIRED',
'DEPOSIT_PAID','INVITED_FOR_QUOTE','QUOTES_RECEIVED',
'ASSIGNED','IN_PROGRESS','COMPLETION_PENDING','VERIFIED','CLOSED','CANCELLED'
];
foreach ($statuses as $status):
?>
<option value="<?= $status ?>" <?= ($job['status'] === $status) ? 'selected' : '' ?>>
<?= $status ?>
</option>
<?php endforeach; ?>
</select>

<br>

<input type="number" step="0.01"
name="deposit_required"
value="<?= htmlspecialchars($job['deposit_required']) ?>"
class="form-control">

<br>
<button class="btn-primary" name="update_job">Update</button>
</form>

<hr>
<hr>

<h4>Invite Installers</h4>

<?php if ($job['status'] === 'SUBMITTED' || $job['status'] === 'INVITED_FOR_QUOTE'): ?>

<form method="POST">

    <label>Invite Expires At</label>
    <input type="datetime-local" name="expires_at" class="form-control">

    <br>

    <label>Select Installers</label>

    <div style="max-height:200px;overflow-y:auto;border:1px solid #ddd;padding:10px;">
        <?php foreach ($installers as $installer): ?>
            <div>
                <label>
                    <input type="checkbox" name="installer_ids[]" value="<?= $installer['id'] ?>">
                    <?= htmlspecialchars($installer['full_name']) ?>
                    (<?= htmlspecialchars($installer['trade']) ?> —
                     <?= htmlspecialchars($installer['base_city']) ?>)
                </label>
            </div>
        <?php endforeach; ?>
    </div>

    <br>

    <button type="submit" name="send_invites" class="btn-primary">
        Send Invites
    </button>

</form>

<?php else: ?>
<p>Invites can only be sent when job is SUBMITTED or INVITED_FOR_QUOTE.</p>
<?php endif; ?>

<h4>Existing Invites</h4>

<?php if (empty($existingInvites)): ?>
<p>No invites sent yet.</p>
<?php else: ?>
<table class="table">
<tr><th>Installer</th><th>Status</th><th>Expires</th></tr>
<?php foreach ($existingInvites as $inv): ?>
<tr>
<td><?= htmlspecialchars($inv['full_name']) ?></td>
<td><?= htmlspecialchars($inv['status']) ?></td>
<td><?= htmlspecialchars($inv['expires_at']) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<hr>

<h4>Quotes Received</h4>

<?php if (empty($quotes)): ?>
<p>No quotes submitted yet.</p>
<?php else: ?>
<table class="table">
<tr>
<th>Installer</th>
<th>Amount</th>
<th>ETA</th>
<th>Status</th>
<th></th>
</tr>
<?php foreach ($quotes as $quote): ?>
<tr>
<td><?= htmlspecialchars($quote['full_name']) ?></td>
<td>R <?= number_format($quote['quote_amount'],2) ?></td>
<td><?= (int)$quote['eta_days'] ?> days</td>
<td><?= htmlspecialchars($quote['status']) ?></td>
<td>
<?php if ($quote['status'] === 'SUBMITTED'): ?>
<form method="POST">
<input type="hidden" name="accept_quote_id" value="<?= $quote['id'] ?>">
<button class="btn-primary btn-sm">Accept</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<hr>

<!-- ======================================================
     C: ISO AUDIT LOG VIEW
====================================================== -->
<h4>ISO Audit Log</h4>

<?php if (empty($auditRows)): ?>
    <p style="color:#666;">No audit entries yet (or audit table not created).</p>
<?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>When</th>
                    <th>Action</th>
                    <th>By</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($auditRows as $a): ?>
                <tr>
                    <td><?= htmlspecialchars($a['performed_at'] ?? '') ?></td>
                    <td><?= htmlspecialchars($a['action'] ?? '') ?></td>
                    <td><?= htmlspecialchars($a['full_name'] ?? 'System') ?></td>
                    <td><?= htmlspecialchars($a['details'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

</div>
</div>

<?php require_once __DIR__ . '/../../../includes/footer.php'; ?>