<?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;

// Validate token if provided
if ($token) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        // 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 = ?
        ");
        $stmt->execute([$token]);
        $reset = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($reset) {
            // Check if token is expired
            $expires = new DateTime($reset['expires_at']);
            $now = new DateTime();
            
            if ($expires > $now) {
                $validToken = true;
                $userId = $reset['user_id'];
                $userEmail = $reset['email'];
                $userName = $reset['first_name'];
            } else {
                $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' && isset($_POST['pin']) && isset($_POST['confirm_pin'])) {
    $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();
            
            // Get user ID from token
            $stmt = $db->prepare("
                SELECT pr.user_id 
                FROM pin_reset_tokens pr
                WHERE pr.token = ?
            ");
            $stmt->execute([$token]);
            $reset = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($reset) {
                $userId = $reset['user_id'];
                
                // 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");
                }
            } else {
                $message = "Invalid reset token.";
            }
        } catch (Exception $e) {
            $message = "An error occurred while resetting your PIN. Please try again.";
            error_log("Error resetting PIN: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset PIN - Ocean Bank Cooperation</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: #2563eb;
            --secondary-color: #1e40af;
        }

        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;
        }

        .btn-primary {
            background: var(--primary-color);
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
        }

        .btn-primary:hover {
            background: var(--secondary-color);
        }

        .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="assets/images/logo.png" alt="Bank 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>
    </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 ($token): ?>
        <form method="post">
            <div class="mb-3">
                <label class="form-label">New PIN</label>
                <input type="password" class="form-control" name="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" 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="text-center mt-3">
        <a href="login.php" class="text-primary">Back to Login</a>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const pinInputs = document.querySelectorAll('input[type="password"]');
    
    pinInputs.forEach(input => {
        input.addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').substring(0, 4);
        });
    });
});
</script>

</body>
</html>
