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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $payment_method = trim($_POST['payment_method'] ?? '');
    $account_info = trim($_POST['account_info'] ?? '');

    if (empty($email) || empty($payment_method) || empty($account_info)) {
        die('Missing required fields.');
    }

    // Check if applicant exists and get their name + current payroll info + message
    $stmt = $pdo->prepare("SELECT full_name, account_info, payroll_message FROM applications WHERE email = ?");
    $stmt->execute([$email]);
    $applicant = $stmt->fetch();

    if (!$applicant) {
        die('Applicant not found.');
    }

    if (!empty($applicant['account_info'])) {
        echo "<script>alert('Payroll already submitted for this applicant.'); history.back();</script>";
        exit;
    }

    // Update payroll info for this applicant
    $stmt = $pdo->prepare("UPDATE applications SET payment_method = ?, account_info = ? WHERE email = ?");
    $success = $stmt->execute([
        $payment_method,
        htmlspecialchars($account_info),
        $email
    ]);

    if ($success):
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Processing Payroll</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" />
      <!-- Font Awesome CDN -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body.modal-open {
            overflow: hidden;
        }
        .modal-backdrop-custom {
            position: fixed;
            inset: 0;
            background-color:#e9edee;
            z-index: 1040;
            opacity: 0;
            animation: fadeInBackdrop 0.3s forwards;
        }
        @keyframes fadeInBackdrop {
            to { opacity: 1; }
        }
        .modal-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.95);
            background: #e9edee;
            padding: 2rem 2.5rem;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            text-align: center;
            z-index: 1050;
            width: 90%;
            max-width: 360px;
            opacity: 0;
            animation: fadeScaleIn 0.4s forwards;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
                Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
        }
        @keyframes fadeScaleIn {
            to {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
        }
        #spinner {
            display: flex !important;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
            width: 3rem;
            height: 3rem;
            transition: opacity 0.5s ease;
            opacity: 1;
        }
        #spinner.hidden {
            opacity: 0;
            pointer-events: none;
        }
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
        #checkmark {
            margin: 0.5rem auto 0 auto;
            opacity: 0;
            transition: opacity 0.5s ease;
            display: none;
            user-select: none;
            width: 3.5rem;
            height: 3.5rem;
        }
        #checkmark.visible {
            display: block;
            opacity: 1;
        }
        #statusText {
            margin-top: 1rem;
            font-weight: 600;
            font-size: 1.3rem;
            color: #28a745;
        }
        #subText {
            margin-top: 0.3rem;
            color: #6c757d;
            font-size: 0.95rem;
        }
        /* Second modal styles */
        #payrollMessageModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.95);
            background:#e9edee;
            padding: 1.8rem 2rem;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            text-align: center;
            z-index: 1060;
            width: 90%;
            max-width: 400px;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.4s ease, transform 0.4s ease;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
                Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
        }
        #payrollMessageModal.show {
            opacity: 1;
            pointer-events: auto;
            transform: translate(-50%, -50%) scale(1);
        }
        #payrollMessageModal h5 {
            margin-bottom: 1rem;
            color: #343a40;
        }
        #payrollMessageModal p {
            color:#142643;
            white-space: pre-wrap;
            margin-bottom: 1.5rem;
        }

          .brand {
      font-family: Arial, sans-serif;
      font-size: 24px;
      font-weight: bold;
      color: #1E2A38;
    }

     i {
      color: #3BA2B8;
      font-size: 28px;
    }

      .check-icon {
      width: 28px;
      height: 28px;
    }
    </style>
</head>
<body class="modal-open">
    <div class="modal-backdrop-custom" style="background-color: #e9edee;"></div>

    <!-- First modal -->
    <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="statusText">
        <div id="spinner" class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Processing...</span>
        </div>

        <svg id="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#28a745" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <path d="M20 6L9 17l-5-5"/>
        </svg>

        <h5 id="statusText">Submitting Payroll...</h5>
        <p id="subText">Please wait a moment</p>
    </div>

   <!-- Second modal -->
<div id="payrollMessageModal" role="dialog" aria-modal="true" aria-labelledby="payrollMessageTitle" aria-describedby="payrollMessageContent">
  <div class="brand">
   <!-- SVG Check Icon -->
    <svg class="check-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="12" cy="12" r="10" stroke="#3BA2B8" stroke-width="2" fill="none"/>
      <path d="M8 12L11 15L16 9" stroke="#3BA2B8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    ManageMe.pro
  </div>   <br>
   <h5 id="payrollMessageTitle">Payroll Verification Notice</h5>
    <?php
$rawMessage = $applicant['payroll_message'] ?: 'No message provided.';

// Escape HTML, convert #text# to <strong>text</strong>, and newlines to <br>
$escaped = htmlspecialchars($rawMessage);
$withBold = preg_replace('/#(.*?)#/', '<strong>$1</strong>', $escaped);
$formattedMessage = nl2br($withBold);
?>
<p id="payrollMessageContent"><?= $formattedMessage ?></p>

    
    <button id="copyMessageBtn" class="btn btn-outline-secondary w-100 mb-2" style="color: #142643; border-color: #142643;">Copy Message</button>
    <div id="copyFeedback" class="text-success fw-semibold mb-2" style="display: none;">Copied!</div>
    
    <button id="closePayrollMessage" class="btn btn-primary w-100" style="background:#142643; border-color: #e9edee; color: #e9edee;">Close</button>
</div>


    <script>
        setTimeout(() => {
            const spinner = document.getElementById('spinner');
            const checkmark = document.getElementById('checkmark');
            const statusText = document.getElementById('statusText');
            const subText = document.getElementById('subText');

            spinner.classList.add('hidden');

            setTimeout(() => {
                spinner.style.display = 'none';
                checkmark.classList.add('visible');
            }, 500);

            statusText.textContent = "Payroll Submitted!";
            subText.textContent = "Loading message...";
        }, 2500);

        // Show second modal after the first modal animation finishes
        setTimeout(() => {
            const payrollModal = document.getElementById('payrollMessageModal');
            payrollModal.classList.add('show');

            // Disable first modal elements (optional)
            const firstModal = document.querySelector('.modal-container');
            if (firstModal) firstModal.style.display = 'none';

            // Remove spinner, checkmark etc from first modal to avoid confusion
            const backdrop = document.querySelector('.modal-backdrop-custom');
            if (backdrop) backdrop.style.backgroundColor = 'rgba(0,0,0,0.6)';
        }, 3500);

        // Close button handler
        document.getElementById('closePayrollMessage').addEventListener('click', () => {
            const payrollModal = document.getElementById('payrollMessageModal');
            payrollModal.classList.remove('show');
            setTimeout(() => {
                window.location.href = '../index.php';
            }, 300);
        });
        
        // Copy button handler
document.getElementById('copyMessageBtn').addEventListener('click', () => {
    const messageText = document.getElementById('payrollMessageContent').innerText;
    navigator.clipboard.writeText(messageText).then(() => {
        const feedback = document.getElementById('copyFeedback');
        feedback.style.display = 'block';
        setTimeout(() => {
            feedback.style.display = 'none';
        }, 2000);
    }).catch(err => {
        alert('Failed to copy message.');
    });
});

    </script>
    
    
</body>
</html>





<?php
    else:
        echo "<script>alert('Failed to save payroll info.'); history.back();</script>";
    endif;
} else {
    echo "Invalid request method.";
}
?>
