<?php
require_once '../../includes/db.php';

// Load PHPMailer classes
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) die("Invalid application ID.");

// Fetch application with celebrity name joined
$stmt = $pdo->prepare("
    SELECT a.*, c.name AS celebrity_name 
    FROM applications a 
    LEFT JOIN celebrities c ON a.celebrity_id = c.id 
    WHERE a.id = ?");
$stmt->execute([$id]);
$app = $stmt->fetch();

if (!$app) die("Application not found.");

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payroll_msg = trim($_POST['payroll_message'] ?? '');
    $action = $_POST['action'] ?? '';

    if ($app['status'] === 'pending') {
        if (empty($payroll_msg)) {
            $message = "<div class='alert alert-danger'>Payroll message is required.</div>";
        } elseif (!in_array($action, ['approve', 'decline'])) {
            $message = "<div class='alert alert-danger'>Invalid action.</div>";
        } else {
            $status = $action === 'approve' ? 'approved' : 'declined';
            $update = $pdo->prepare("UPDATE applications SET status = ?, payroll_message = ? WHERE id = ?");
            $update->execute([$status, $payroll_msg, $id]);

            // Send email on approval
            if ($action === 'approve') {
        // Send Welcome Email Using PHPMailer
        $mail = new PHPMailer(true);
        try {
           $submitLink = "https://manageme.pro/public/payroll/setup.php?email=" . urlencode($app['email']);

            // Server settings
            $mail->isSMTP();
            $mail->Host       = 'mail.spacemail.com';      // Replace with your SMTP server
            $mail->SMTPAuth   = true;
            $mail->Username   = 'support@manageme.pro';        // Your SMTP email
            $mail->Password   = '#Admin404';          // Your SMTP password
            $mail->SMTPSecure = 'ssl';
            $mail->Port       = 465;

            // Recipients
            $mail->setFrom('support@manageme.pro', 'ManageMe');
            $mail->addAddress($app['email'], $app['fullname']);

            // Content
            $mail->isHTML(true);
            $mail->Subject = "Management Team";
            $mail->Body    = "
                <div style='background: #f0f0f0; padding: 20px; font-family: Arial, sans-serif;'>
                    <div style='background: #fff; padding: 20px; border-radius: 10px;'>
                        <h2 style='color: #333;'>Welcome</h2>
                        <p>Hello {$app['full_name']},

We are pleased to inform you that your application to join the {$app['celebrity_name']} Management Team has been approved.

Please complete your onboarding by submitting your payment and payroll details through our secure setup portal:</p>
                       
                        </ul>
                             <a href='" . $submitLink . "' style='display: inline-block; background: #007BFF; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none;'>Submit Payroll Details</a>

                        <p style='margin-top: 20px;'>Cheers,<br>
                        If you have any questions, feel free to contact us at support@manageme.pro.

Welcome to the team!

Best regards,
The {$app['celebrity_name']} Team
                    </div>
                </div>
            ";

            $mail->send();
                } catch (Exception $e) {
                    $message = "<div class='alert alert-warning'>Application approved but email could not be sent. Error: {$mail->ErrorInfo}</div>";
                }
            }

            if (!$message) {
                $message = "<div class='alert alert-success'>Application has been <strong>" . ucfirst($status) . "</strong>.</div>";
            }
        }
    } else {
        // Only payroll message update allowed after status decided
        if ($payroll_msg === '') {
            $message = "<div class='alert alert-danger'>Payroll message is required.</div>";
        } else {
            $update = $pdo->prepare("UPDATE applications SET payroll_message = ? WHERE id = ?");
            $update->execute([$payroll_msg, $id]);
            $message = "<div class='alert alert-success'>Payroll message updated successfully.</div>";
        }
    }

    // Refresh application data after POST
    $stmt->execute([$id]);
    $app = $stmt->fetch();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>View Application - <?= htmlspecialchars($app['full_name']) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body { background: #f1f3f7; font-family: system-ui, sans-serif; min-height: 100vh; }
    .container { max-width: 850px; margin: 70px auto 30px; background: #fff; border-radius: 10px; padding: 30px; box-shadow: 0 0 15px rgba(0,0,0,0.05); }
    .label-title { font-weight: 600; color: #333; }
    textarea.form-control { resize: vertical; }
    @media (max-width: 576px) { .container { padding: 20px 15px; } }
  </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container mt-4">
  <h2>Application Details</h2>

  <?= $message ?>

  <p><span class="label-title">Full Name:</span> <?= htmlspecialchars($app['full_name']) ?></p>
  <p><span class="label-title">Email:</span> <?= htmlspecialchars($app['email']) ?></p>
  <p><span class="label-title">Phone:</span> <?= htmlspecialchars($app['phone']) ?></p>
  <p><span class="label-title">Role:</span> <?= htmlspecialchars($app['role']) ?></p>
  <p><span class="label-title">Location:</span> <?= htmlspecialchars($app['location']) ?></p>
  <p><span class="label-title">Medical Condition:</span> <?= htmlspecialchars($app['condition']) ?></p>
  <p><span class="label-title">Date of Birth:</span> <?= htmlspecialchars($app['dob']) ?></p>
  <p><span class="label-title">Bio:</span><br><?= nl2br(htmlspecialchars($app['bio'])) ?></p>
  <p><span class="label-title">Experience:</span><br><?= nl2br(htmlspecialchars($app['experience'])) ?></p>
  <p><span class="label-title">Why this job:</span><br><?= nl2br(htmlspecialchars($app['why'])) ?></p>

  <p><span class="label-title">Status:</span>
    <span class="badge bg-<?= $app['status'] === 'approved' ? 'success' : ($app['status'] === 'declined' ? 'danger' : 'warning') ?>">
      <?= ucfirst($app['status']) ?>
    </span>
  </p>

<?php if (!empty($app['idcard'])): ?>
  <p><span class="label-title">ID Card:</span></p>
  <div>
    <img 
      src="../images/idcards/<?= htmlspecialchars($app['idcard']) ?>" 
      alt="Applicant ID Card" 
      class="img-fluid rounded border"
      style="max-width: 400px;"
    />
    <div class="mt-2">
      <a href="../images/idcards/<?= htmlspecialchars($app['idcard']) ?>" target="_blank" class="btn btn-outline-primary btn-sm">
        View Full ID
      </a>
    </div>
  </div>
<?php else: ?>
  <p><span class="label-title">ID Card:</span> Not provided</p>
<?php endif; ?>


  <form method="post" class="mt-4">
    <div class="mb-3">
      <label for="payroll_message" class="form-label">Payroll Message <span class="text-danger">*</span></label>
      <textarea name="payroll_message" id="payroll_message" class="form-control" rows="4" required><?= htmlspecialchars($_POST['payroll_message'] ?? $app['payroll_message']) ?></textarea>
    </div>

    <?php if ($app['status'] === 'pending'): ?>
      <div class="d-flex gap-3">
        <button type="submit" name="action" value="approve" class="btn btn-success">Approve</button>
        <button type="submit" name="action" value="decline" class="btn btn-danger">Decline</button>
      </div>
    <?php else: ?>
      <button type="submit" class="btn btn-primary">Update Message</button>
    <?php endif; ?>
  </form>

  <hr>

  <h4>Payroll Email Preview</h4>
  <div class="mb-3">
    <textarea class="form-control" rows="14" readonly style="background:#f8f9fa; font-family: monospace;"><?= htmlspecialchars(
        "Hello {$app['full_name']},\n\n" .
        "We are pleased to inform you that your application to join the {$app['celebrity_name']}'s Management Team has been approved.\n\n" .
        "Please complete your onboarding by submitting your payment and payroll details through our secure setup portal:\n" .
        "https://manageme.pro/public/payroll/setup.php?email=" . urlencode($app['email']) . "\n\n" .
        "If you have any questions, feel free to contact us at support@manageme.com.\n\n" .
        "Welcome to the team!\n\n" .
        "Best regards,\n" .
        "The {$app['celebrity_name']} Team"
    ) ?></textarea>
  </div>

  <a href="index.php" class="btn btn-secondary mt-3">&larr; Back to List</a>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
