<?php
session_start();
require_once 'config/database.php';

// Set the default timezone
date_default_timezone_set('UTC');

// Get token from URL
$token = filter_input(INPUT_GET, 'token');

// Initialize variables
$message = '';
$messageType = 'danger';
$validToken = false;
$resetComplete = false;
$userId = null;
$userEmail = null;

// Generate CSRF token if it doesn't exist
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Validate token if provided
if ($token) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        // In reset-pin.php
        $email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
$token = filter_input(INPUT_GET, 'token');
        
        // Check if token exists and is valid
        $stmt = $db->prepare("
            SELECT pr.*, u.email, u.first_name 
            FROM pin_reset_tokens pr
            JOIN users u ON pr.user_id = u.id
            WHERE pr.token = ? AND pr.expires_at > NOW()
        ");
        $stmt->execute([$token]);
        $reset = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($reset) {
            $validToken = true;
            $userId = $reset['user_id'];
            $userEmail = $reset['email'];
            $userName = $reset['first_name'];
        } else {
            // Check if token exists but is expired
            $stmt = $db->prepare("
                SELECT pr.*, u.email 
                FROM pin_reset_tokens pr
                JOIN users u ON pr.user_id = u.id
                WHERE pr.token = ?
            ");
            $stmt->execute([$token]);
            $expired = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($expired) {
                $message = "Your PIN reset link has expired. Please request a new one.";
            } else {
                $message = "Invalid PIN reset link. Please request a new one.";
            }
        }
    } catch (Exception $e) {
        $message = "An error occurred. Please try again.";
        error_log("Error validating reset token: " . $e->getMessage());
    }
} else {
    $message = "Invalid request. Please use the link from your email.";
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $validToken) {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $message = "Invalid form submission. Please try again.";
    } else {
        $pin = $_POST['pin'] ?? '';
        $confirm_pin = $_POST['confirm_pin'] ?? '';
        
        // Validate PIN
        if (strlen($pin) !== 4 || !ctype_digit($pin)) {
            $message = "PIN must be exactly 4 digits.";
        } elseif ($pin !== $confirm_pin) {
            $message = "PINs do not match.";
        } else {
            try {
                $database = new Database();
                $db = $database->getConnection();
                
                // Update user's PIN
                $hashedPin = password_hash($pin, PASSWORD_DEFAULT);
                $stmt = $db->prepare("UPDATE users SET pin = ? WHERE id = ?");
                $result = $stmt->execute([$hashedPin, $userId]);
                
                if ($result) {
                    // Delete the used reset token
                    $stmt = $db->prepare("DELETE FROM pin_reset_tokens WHERE user_id = ?");
                    $stmt->execute([$userId]);
                    
                    $message = "Your PIN has been reset successfully!";
                    $messageType = "success";
                    $resetComplete = true;
                    
                    // Log the successful PIN reset
                    error_log("PIN reset successful for user ID: $userId");
                } else {
                    $message = "Failed to update PIN. Please try again.";
                    error_log("Failed to update PIN for user ID: $userId");
                }
            } catch (Exception $e) {
                $message = "An error occurred while resetting your PIN. Please try again.";
                error_log("Error resetting PIN: " . $e->getMessage());
            }
        }
    }
}

// Bank branding variables - you can define these in your config file
$bankName = defined('BANK_NAME') ? BANK_NAME : 'Ocean Bank Cooperation';
$bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'assets/images/logo.png';
$primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
$secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset PIN - <?php echo htmlspecialchars($bankName); ?></title>
    
    <!-- CSS Dependencies -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: <?php echo $primaryColor; ?>;
            --secondary-color: <?php echo $secondaryColor; ?>;
            --background-color: #f0f2f5;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

        .reset-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 2rem;
            max-width: 500px;
            width: 100%;
        }

        .brand-logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .brand-logo img {
            height: 50px;
        }

        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            font-size: 0.95rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: none;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary-color);
            border: none;
        }

        .btn-primary:hover {
            background: var(--secondary-color);
            transform: translateY(-2px);
        }

        .back-to-login {
            text-align: center;
            margin-top: 1.5rem;
        }

        .back-to-login a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .back-to-login a:hover {
            color: var(--secondary-color);
        }
        
        .pin-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1.5rem;
        }
        
        .pin-input {
            width: 60px;
            height: 60px;
            text-align: center;
            font-size: 1.5rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            margin: 0 5px;
        }
        
        .pin-input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(37, 99, 235, 0.1);
        }
        
        .pin-requirements {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 0.9rem;
        }
        
        .icon-container {
            width: 80px;
            height: 80px;
            margin: 0 auto 1.5rem;
            background-color: #f0f9ff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .icon-container i {
            font-size: 2.5rem;
            color: var(--primary-color);
        }
    </style>
</head>
<body>

<div class="reset-card">
    <div class="brand-logo">
        <img src="<?php echo htmlspecialchars($bankLogo); ?>" alt="<?php echo htmlspecialchars($bankName); ?> Logo">
    </div>

    <div class="text-center mb-4">
        <div class="icon-container">
            <i class='bx bx-lock-open'></i>
        </div>
        <h4>Reset Your PIN</h4>
        <?php if ($validToken && !$resetComplete): ?>
        <p class="text-muted">Please enter a new 4-digit PIN for your account</p>
        <?php endif; ?>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>" role="alert">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
    
    <?php if ($resetComplete): ?>
        <div class="text-center mt-4">
            <p>You can now log in with your new PIN.</p>
            <a href="login.php" class="btn btn-primary">Go to Login</a>
        </div>
    <?php elseif ($validToken): ?>
        <div class="pin-requirements mb-4">
            <h6>PIN Requirements:</h6>
            <ul>
                <li>Must be exactly 4 digits</li>
                <li>Use a PIN that you can remember but is not easily guessable</li>
                <li>Do not use sequential numbers (e.g., 1234) or repeated digits (e.g., 1111)</li>
            </ul>
        </div>
        
        <form method="post" id="resetForm">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            
            <div class="mb-3">
                <label class="form-label">New PIN</label>
                <input type="password" class="form-control" name="pin" id="pin" required 
                       minlength="4" maxlength="4" pattern="[0-9]{4}" 
                       inputmode="numeric" autocomplete="off">
                <small class="text-muted">Enter a 4-digit PIN</small>
            </div>
            
            <div class="mb-4">
                <label class="form-label">Confirm PIN</label>
                <input type="password" class="form-control" name="confirm_pin" id="confirm_pin" required 
                       minlength="4" maxlength="4" pattern="[0-9]{4}" 
                       inputmode="numeric" autocomplete="off">
            </div>
            
            <button type="submit" class="btn btn-primary w-100">Reset PIN</button>
        </form>
    <?php else: ?>
        <div class="text-center mt-4">
            <p>The PIN reset link is invalid or has expired.</p>
            <a href="forgot-pin.php" class="btn btn-primary">Request New Reset Link</a>
        </div>
    <?php endif; ?>

    <div class="back-to-login">
        <a href="login.php"><i class='bx bx-arrow-back'></i> Back to Login</a>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const pinInput = document.getElementById('pin');
    const confirmPinInput = document.getElementById('confirm_pin');
    const form = document.getElementById('resetForm');
    
    // Only allow numbers in PIN fields
    if (pinInput) {
        pinInput.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
    
    if (confirmPinInput) {
        confirmPinInput.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
    
    // Validate PIN format and matching
    if (form) {
        form.addEventListener('submit', function(e) {
            const pin = pinInput.value;
            const confirmPin = confirmPinInput.value;
            
            // Check if PIN is 4 digits
            if (!/^\d{4}$/.test(pin)) {
                e.preventDefault();
                alert('PIN must be exactly 4 digits.');
                return;
            }
            
            // Check for sequential numbers
            if (pin === '1234' || pin === '2345' || pin === '3456' || pin === '4567' || 
                pin === '5678' || pin === '6789' || pin === '0123') {
                if (!confirm('Your PIN appears to be sequential numbers, which is not secure. Are you sure you want to use this PIN?')) {
                    e.preventDefault();
                    return;
                }
            }
            
            // Check for repeated digits
            if (pin === '0000' || pin === '1111' || pin === '2222' || pin === '3333' || 
                pin === '4444' || pin === '5555' || pin === '6666' || pin === '7777' || 
                pin === '8888' || pin === '9999') {
                if (!confirm('Your PIN appears to be repeated digits, which is not secure. Are you sure you want to use this PIN?')) {
                    e.preventDefault();
                    return;
                }
            }
            
            // Check if PINs match
            if (pin !== confirmPin) {
                e.preventDefault();
                alert('PINs do not match!');
                return;
            }
        });
    }
});
</script>

</body>
</html>
