<?php
/**
 * Store Owner Password Change Page
 * Allows store owners to change their account password
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/SessionManager.php';
use App\classes\SessionManager;

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$userId = $_SESSION['user_id'];

// SECURITY: Validate session to prevent session hijacking
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($userId);

if (!$sessionValidation['valid']) {
    error_log("Invalid session detected - User ID: $userId, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header("Location: ../login.php?error=session_invalid");
    exit();
}

// MULTI-LAYER SECURITY CHECK: Verify user is actually a store owner
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

if (!$verification['valid']) {
    error_log("Store Change Password Access Denied - User ID: $userId, Reason: " . $verification['reason']);
    header("Location: ../user_index.php");
    exit();
}

// Get store owner info
$userStmt = $conn->prepare("SELECT id, username, email FROM agents WHERE id = ?");
$userStmt->bind_param("i", $userId);
$userStmt->execute();
$userResult = $userStmt->get_result();
$user = $userResult->fetch_assoc();
$userStmt->close();

if (!$user) {
    header("Location: ../logout.php");
    exit();
}

$error_message = '';
$success_message = '';

// Handle password change form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validate input
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error_message = 'Please fill in all fields.';
    } elseif ($new_password !== $confirm_password) {
        $error_message = 'New passwords do not match.';
    } elseif (strlen($new_password) < 6) {
        $error_message = 'New password must be at least 6 characters long.';
    } else {
        // Get current password hash
        $stmt = $conn->prepare("SELECT password_hash FROM agents WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $userData = $result->fetch_assoc();
            
            // Verify current password
            if (password_verify($current_password, $userData['password_hash'])) {
                // Update password
                $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                
                $update_stmt = $conn->prepare("UPDATE agents SET password_hash = ? WHERE id = ?");
                $update_stmt->bind_param("si", $new_password_hash, $userId);
                
                if ($update_stmt->execute()) {
                    $success_message = 'Password changed successfully! You may need to log in again.';
                    // Log password change for security
                    error_log("Store owner password changed - User ID: $userId, Username: " . $user['username']);
                } else {
                    $error_message = 'Failed to update password. Please try again.';
                }
                $update_stmt->close();
            } else {
                $error_message = 'Current password is incorrect.';
            }
        } else {
            $error_message = 'User not found. Please try again.';
        }
        $stmt->close();
    }
}

// Get store info for navigation
$store = $storeManager->getStoreByOwnerId($userId);

// Include reusable navigation
require_once 'includes/store_nav.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Change Password - <?php echo htmlspecialchars($store['store_name'] ?? 'My Store'); ?></title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
        }
    </style>
</head>

<body class="bg-gray-900">
    <?php renderStoreNav($store, 'password'); ?>

    <div class="container mx-auto px-3 sm:px-4 py-6 sm:py-8">
        <div class="max-w-2xl mx-auto">
            <!-- Success/Error Messages -->
            <?php if (!empty($success_message)): ?>
                <div class="bg-green-900/20 border border-green-500/30 rounded-lg p-4 mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle text-green-400 mr-3"></i>
                        <span class="text-green-400 font-medium"><?= htmlspecialchars($success_message) ?></span>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($error_message)): ?>
                <div class="bg-red-900/20 border border-red-500/30 rounded-lg p-4 mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-400 mr-3"></i>
                        <span class="text-red-400 font-medium"><?= htmlspecialchars($error_message) ?></span>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Change Password Card -->
            <div class="bg-gray-800 rounded-xl p-6 sm:p-8 border border-gray-700 mb-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl sm:text-2xl font-bold text-white">
                        <i class="fas fa-key text-yellow-400 mr-2"></i>Change Password
                    </h2>
                </div>

                <!-- Password Change Form -->
                <form method="POST" class="space-y-6">
                    <div class="max-w-md mx-auto">
                        <!-- Current Password -->
                        <div class="mb-4">
                            <label for="current_password" class="block text-sm font-medium text-gray-300 mb-2">
                                <i class="fas fa-lock mr-2 text-yellow-400"></i>Current Password
                            </label>
                            <div class="relative">
                                <input type="password" id="current_password" name="current_password" 
                                       class="w-full border border-gray-600 rounded-lg px-4 py-3 pr-10 bg-gray-700 text-white focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500" 
                                       required autocomplete="current-password">
                                <button type="button" onclick="togglePassword('current_password')" 
                                        class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-yellow-400">
                                    <i class="fas fa-eye" id="current_password_icon"></i>
                                </button>
                            </div>
                        </div>

                        <!-- New Password -->
                        <div class="mb-4">
                            <label for="new_password" class="block text-sm font-medium text-gray-300 mb-2">
                                <i class="fas fa-key mr-2 text-yellow-400"></i>New Password
                            </label>
                            <div class="relative">
                                <input type="password" id="new_password" name="new_password" 
                                       class="w-full border border-gray-600 rounded-lg px-4 py-3 pr-10 bg-gray-700 text-white focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500" 
                                       required minlength="6" autocomplete="new-password">
                                <button type="button" onclick="togglePassword('new_password')" 
                                        class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-yellow-400">
                                    <i class="fas fa-eye" id="new_password_icon"></i>
                                </button>
                            </div>
                            <div class="mt-2">
                                <div class="text-xs text-gray-400">
                                    <div class="flex items-center space-x-2">
                                        <span id="length-check" class="flex items-center">
                                            <i class="fas fa-times text-red-400 mr-1"></i>
                                            <span>At least 6 characters</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Confirm New Password -->
                        <div class="mb-6">
                            <label for="confirm_password" class="block text-sm font-medium text-gray-300 mb-2">
                                <i class="fas fa-check-circle mr-2 text-yellow-400"></i>Confirm New Password
                            </label>
                            <div class="relative">
                                <input type="password" id="confirm_password" name="confirm_password" 
                                       class="w-full border border-gray-600 rounded-lg px-4 py-3 pr-10 bg-gray-700 text-white focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500" 
                                       required minlength="6" autocomplete="new-password">
                                <button type="button" onclick="togglePassword('confirm_password')" 
                                        class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-yellow-400">
                                    <i class="fas fa-eye" id="confirm_password_icon"></i>
                                </button>
                            </div>
                            <div class="mt-2">
                                <div class="text-xs text-gray-400">
                                    <div class="flex items-center space-x-2">
                                        <span id="match-check" class="flex items-center">
                                            <i class="fas fa-times text-red-400 mr-1"></i>
                                            <span>Passwords match</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Button -->
                        <div class="flex space-x-3">
                            <button type="submit" name="change_password"
                                    class="flex-1 bg-gradient-to-r from-yellow-500 to-yellow-600 text-white py-3 px-6 rounded-lg font-medium hover:from-yellow-600 hover:to-yellow-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                                    id="submit-btn" disabled>
                                <i class="fas fa-save mr-2"></i>Change Password
                            </button>
                            <a href="store_dashboard.php" 
                               class="flex-1 border border-gray-600 text-gray-300 py-3 px-6 rounded-lg font-medium hover:bg-gray-700 hover:text-white transition-colors text-center">
                                <i class="fas fa-times mr-2"></i>Cancel
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Password Security Tips -->
            <div class="bg-gray-800 rounded-xl p-6 border border-gray-700">
                <h3 class="text-lg font-bold text-white mb-4">
                    <i class="fas fa-shield-alt mr-2 text-yellow-400"></i>Password Security Tips
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="space-y-4">
                        <h4 class="font-semibold text-white">Do's</h4>
                        <div class="space-y-2">
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-check-circle text-green-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Use at least 6 characters (8+ recommended)</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-check-circle text-green-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Include uppercase and lowercase letters</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-check-circle text-green-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Add numbers and special characters</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-check-circle text-green-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Use a unique password for this account</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="space-y-4">
                        <h4 class="font-semibold text-white">Don'ts</h4>
                        <div class="space-y-2">
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-times-circle text-red-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Use personal information</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-times-circle text-red-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Use common words or patterns</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-times-circle text-red-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Share your password with others</span>
                            </div>
                            <div class="flex items-start space-x-2">
                                <i class="fas fa-times-circle text-red-400 mt-1"></i>
                                <span class="text-sm text-gray-400">Use the same password for multiple accounts</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Security Notice -->
            <div class="bg-yellow-900/20 border border-yellow-500/30 rounded-xl p-4 mt-6">
                <div class="flex items-start space-x-3">
                    <i class="fas fa-exclamation-triangle text-yellow-400 mt-1"></i>
                    <div>
                        <h4 class="font-semibold text-yellow-400">Security Notice</h4>
                        <p class="text-sm text-gray-400 mt-1">
                            After changing your password, you may need to log in again on other devices. 
                            Make sure to update any saved passwords in your browser or password manager.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function togglePassword(fieldId) {
            const field = document.getElementById(fieldId);
            const icon = document.getElementById(fieldId + '_icon');
            
            if (field.type === 'password') {
                field.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                field.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
        
        function validatePasswords() {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            const submitBtn = document.getElementById('submit-btn');
            
            // Check length
            const lengthCheck = document.getElementById('length-check');
            if (newPassword.length >= 6) {
                lengthCheck.innerHTML = '<i class="fas fa-check text-green-400 mr-1"></i><span>At least 6 characters</span>';
            } else {
                lengthCheck.innerHTML = '<i class="fas fa-times text-red-400 mr-1"></i><span>At least 6 characters</span>';
            }
            
            // Check match
            const matchCheck = document.getElementById('match-check');
            if (newPassword && confirmPassword && newPassword === confirmPassword) {
                matchCheck.innerHTML = '<i class="fas fa-check text-green-400 mr-1"></i><span>Passwords match</span>';
            } else {
                matchCheck.innerHTML = '<i class="fas fa-times text-red-400 mr-1"></i><span>Passwords match</span>';
            }
            
            // Enable/disable submit button
            if (newPassword.length >= 6 && newPassword === confirmPassword) {
                submitBtn.disabled = false;
            } else {
                submitBtn.disabled = true;
            }
        }
        
        // Add event listeners
        document.getElementById('new_password').addEventListener('input', validatePasswords);
        document.getElementById('confirm_password').addEventListener('input', validatePasswords);
    </script>
</body>
</html>

