<?php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';

requireLogin();
requirePermission('manage_installers');

$companyId = $_SESSION['company_id'] ?? null;
$userId    = $_SESSION['user_id'] ?? null;

if (!$companyId) {
    die("Tenant isolation error.");
}

$appId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($appId <= 0) {
    die("Invalid application ID.");
}

/* ===============================
   FETCH APPLICATION
=================================*/
$stmt = $pdo->prepare("
    SELECT * FROM installer_applications
    WHERE id = ? AND company_id = ?
    LIMIT 1
");
$stmt->execute([$appId, $companyId]);
$app = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$app) {
    die("Application not found or access denied.");
}

/* ===============================
   FETCH DOCUMENTS
=================================*/
$docsStmt = $pdo->prepare("
    SELECT * FROM installer_documents
    WHERE application_id = ?
");
$docsStmt->execute([$appId]);
$documents = $docsStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   HANDLE DOCUMENT VERIFY/REJECT
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['doc_action'])) {

    $docId = (int)$_POST['doc_id'];
    $action = $_POST['doc_action'];

    if ($action === 'verify') {
        $pdo->prepare("
            UPDATE installer_documents
            SET status='VERIFIED',
                verified_by=?,
                verified_at=NOW(),
                rejection_reason=NULL
            WHERE id=?
        ")->execute([$userId, $docId]);
    }

    if ($action === 'reject') {
        $reason = trim($_POST['rejection_reason'] ?? '');
        $pdo->prepare("
            UPDATE installer_documents
            SET status='REJECTED',
                verified_by=?,
                verified_at=NOW(),
                rejection_reason=?
            WHERE id=?
        ")->execute([$userId, $reason, $docId]);
    }

    header("Location: view.php?id=".$appId);
    exit;
}

$error = null;
$success = null;

/* ===============================
   HANDLE APPROVAL / REJECT
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['doc_action'])) {

    if (isset($_POST['approve'])) {

        if ($app['status'] !== 'PENDING') {
            $error = "This application is already processed.";
        } else {

            try {

                $check = $pdo->prepare("
                    SELECT id FROM users
                    WHERE email = ? AND company_id = ?
                    LIMIT 1
                ");
                $check->execute([$app['email'], $companyId]);

                if ($check->fetch()) {
                    $error = "Installer already exists in this company.";
                } else {

                    $pdo->beginTransaction();

                    $tempPassword = bin2hex(random_bytes(4));
                    $passwordHash = password_hash($tempPassword, PASSWORD_DEFAULT);

                    $pdo->prepare("
                        INSERT INTO users
                        (full_name, email, password_hash, role_id, skill_type,
                         availability_status, company_id, status, must_change_password, created_at)
                        VALUES (?, ?, ?, 3, ?, 'AVAILABLE', ?, 'ACTIVE', 1, NOW())
                    ")->execute([
                        $app['full_name'],
                        $app['email'],
                        $passwordHash,
                        $app['trade_skill'],
                        $companyId
                    ]);

                    $pdo->prepare("
                        UPDATE installer_applications
                        SET status='APPROVED'
                        WHERE id=? AND company_id=?
                    ")->execute([$appId, $companyId]);

                    $pdo->commit();

                    $success = "Installer Approved. Temporary Password: " . $tempPassword;

                    $stmt->execute([$appId, $companyId]);
                    $app = $stmt->fetch(PDO::FETCH_ASSOC);
                }

            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $error = "Approval failed: " . $e->getMessage();
            }
        }
    }

    if (isset($_POST['reject'])) {
        $pdo->prepare("
            UPDATE installer_applications
            SET status='REJECTED'
            WHERE id=? AND company_id=?
        ")->execute([$appId, $companyId]);

        header("Location: applications.php");
        exit;
    }
}

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

<div class="main-content">

<div class="page-header" style="display:flex;justify-content:space-between;align-items:center;">
    <div>
        <h2>Installer Application</h2>
        <p class="page-subtitle"><?= htmlspecialchars($app['full_name']) ?></p>
    </div>

    <a href="applications.php" class="btn btn-secondary">
        ← Back to Applications
    </a>
</div>

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

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

<div class="card-form" style="max-width:800px;">

<p><strong>Email:</strong> <?= htmlspecialchars($app['email']) ?></p>
<p><strong>Phone:</strong> <?= htmlspecialchars($app['phone']) ?></p>
<p><strong>City:</strong> <?= htmlspecialchars($app['city']) ?></p>
<p><strong>Trade Skill:</strong> <?= htmlspecialchars($app['trade_skill']) ?></p>
<p><strong>Status:</strong> <?= htmlspecialchars($app['status']) ?></p>

<hr style="margin:30px 0;">

<h3>Uploaded Documents</h3>

<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-top:20px;">

<?php foreach ($documents as $doc): 

$statusColor = '#6b7280';
if ($doc['status']=='VERIFIED') $statusColor='#16a34a';
if ($doc['status']=='REJECTED') $statusColor='#dc2626';
?>

<div style="background:#fff;border-radius:12px;padding:20px;border:1px solid #e5e7eb;box-shadow:0 6px 20px rgba(0,0,0,0.05);">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
<strong><?= htmlspecialchars($doc['document_type']) ?></strong>

<span style="padding:4px 10px;font-size:12px;border-radius:20px;background:<?= $statusColor ?>20;color:<?= $statusColor ?>;font-weight:600;">
<?= $doc['status'] ?>
</span>
</div>

<a href="<?= htmlspecialchars($doc['file_path']) ?>" target="_blank"
style="color:#f2531e;font-weight:600;display:block;margin-bottom:15px;">
Download Document
</a>

<?php if ($doc['status']=='PENDING'): ?>
<form method="POST" style="display:flex;gap:10px;">
<input type="hidden" name="doc_id" value="<?= $doc['id'] ?>">

<button type="submit" name="doc_action" value="verify" class="btn btn-success">
Verify
</button>

<button type="button" onclick="openRejectModal(<?= $doc['id'] ?>)" class="btn btn-danger">
Reject
</button>
</form>
<?php endif; ?>

<?php if ($doc['status']=='REJECTED' && $doc['rejection_reason']): ?>
<div style="margin-top:10px;color:#dc2626;font-size:13px;">
Reason: <?= htmlspecialchars($doc['rejection_reason']) ?>
</div>
<?php endif; ?>

</div>

<?php endforeach; ?>
</div>

<hr style="margin:30px 0;">

<?php if ($app['status'] === 'PENDING'): ?>
<form method="POST">
<button type="submit" name="approve" class="btn btn-primary">
Approve & Create Installer
</button>

<button type="submit" name="reject" class="btn btn-danger">
Reject Application
</button>
</form>
<?php else: ?>
<p>This application is already processed.</p>
<?php endif; ?>

</div>
</div>

<!-- REJECTION MODAL -->
<div id="rejectModal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);justify-content:center;align-items:center;z-index:999;">
<div style="background:white;padding:25px;border-radius:12px;width:400px;">
<h3>Reject Document</h3>
<form method="POST">
<input type="hidden" name="doc_id" id="rejectDocId">
<input type="hidden" name="doc_action" value="reject">
<textarea name="rejection_reason" required style="width:100%;padding:10px;border-radius:8px;border:1px solid #ccc;margin-bottom:15px;" placeholder="Enter rejection reason..."></textarea>
<div style="display:flex;justify-content:flex-end;gap:10px;">
<button type="button" onclick="closeRejectModal()" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-danger">Confirm Reject</button>
</div>
</form>
</div>
</div>

<script>
function openRejectModal(id){
document.getElementById('rejectModal').style.display='flex';
document.getElementById('rejectDocId').value=id;
}
function closeRejectModal(){
document.getElementById('rejectModal').style.display='none';
}
</script>

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