<?php
session_start();
require_once 'system/conn.php';

// 1. Redirect if already logged in
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: home.php');
    exit;
}

// 2. Generate CSRF Token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$errors = [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    // 3. CSRF Security Check
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = 'Session expired. Please refresh the page.';
    } 
    // Validate inputs
    elseif (empty($_POST['branch']) || empty($_POST['username']) || empty($_POST['password'])) {
        $errors[] = 'All fields are required.';
    } else {

        $branch   = (int) $_POST['branch'];
        $username = trim($_POST['username']);
        $password = $_POST['password'];

        // Fetch user details
        $sql = "SELECT id, username, password, name 
                FROM branch 
                WHERE id = :branch 
                AND username = :username 
                AND status = 1 
                LIMIT 1";

        $stmt = $conn->prepare($sql);
        $stmt->execute([
            ':branch'   => $branch,
            ':username' => $username
        ]);

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // 4. Verify Password
        if ($user && password_verify($password, $user['password'])) {
            
            session_regenerate_id(true); 
            
            $_SESSION['user_id']     = $user['id'];
            $_SESSION['username']    = $user['username'];
            
            // FIXED: Reverted back to 'branch' to match your existing home.php
            $_SESSION['branch']      = $branch; 
            
            $_SESSION['branch_name'] = $user['name']; 
            $_SESSION['logged_in']   = true;
            
            header('Location: home.php');
            exit;
        } else {
            $errors[] = 'Invalid branch, username, or password.';
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login | Utkal Team Care</title>
    
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body {
            /* Brand Gradient */
            background: linear-gradient(135deg, #005bea 0%, #00c6fb 100%);
            font-family: 'Inter', sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
        }
        
        .login-card {
            width: 100%;
            max-width: 450px;
            background: #ffffff;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2); 
            padding: 45px 40px;
            border: none;
        }

        .logo-area {
            text-align: center;
            margin-bottom: 35px;
        }
        
        .logo-area img {
            height: 75px; 
            width: auto;
            margin-bottom: 15px;
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        
        .logo-area h5 {
            font-weight: 700;
            color: #1e293b;
            margin: 0;
            font-size: 1.5rem;
        }

        .form-label {
            font-weight: 600;
            font-size: 0.9rem;
            color: #475569;
            margin-bottom: 8px;
        }

        .form-control {
            padding: 12px 16px;
            border-radius: 8px;
            border: 1px solid #cbd5e1;
            font-size: 1rem;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
            outline: none;
        }

        /* Select2 Fixes */
        .select2-container .select2-selection--single {
            height: 48px !important;
            border: 1px solid #cbd5e1 !important;
            border-radius: 8px !important;
            display: flex;
            align-items: center;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px !important;
            right: 10px !important;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            padding-left: 16px !important;
            font-size: 1rem !important;
            color: #334155 !important;
        }

        .btn-login {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border: none;
            color: white;
            padding: 14px;
            font-weight: 600;
            font-size: 1.05rem;
            width: 100%;
            border-radius: 8px;
            margin-top: 5px;
            cursor: pointer;
            transition: opacity 0.2s;
        }
        
        .btn-login:hover {
            opacity: 0.9;
        }

        /* Style for the secondary Superadmin button */
        .btn-superadmin {
            background: #f1f5f9;
            color: #475569;
            border: 1px solid #cbd5e1;
            padding: 12px;
            font-weight: 600;
            width: 100%;
            border-radius: 8px;
            margin-top: 15px;
            display: block;
            text-align: center;
            text-decoration: none;
            transition: all 0.2s;
        }

        .btn-superadmin:hover {
            background: #e2e8f0;
            color: #1e293b;
        }

        .forgot-password-link {
            font-size: 0.85rem;
            color: #64748b;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.2s;
            cursor: pointer;
        }
        
        .forgot-password-link:hover {
            color: #2563eb;
            text-decoration: underline;
        }

        .alert-custom {
            font-size: 0.9rem;
            padding: 12px;
            border-radius: 8px;
            background-color: #fef2f2;
            color: #b91c1c;
            border: 1px solid #fecaca;
        }
        
        .copyright {
            text-align: center;
            font-size: 0.8rem;
            color: rgba(255,255,255,0.7); 
            margin-top: 20px;
        }
    </style>
</head>

<body>

    <div class="d-flex flex-column align-items-center w-100">
        <div class="login-card">
            
            <div class="logo-area">
                <img src="https://utcpl.co.in/images/logo-1.webp" alt="Utkal Team Care Logo">
                <h5>Branch Login</h5>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-custom mb-4">
                    <ul class="mb-0 ps-3">
                        <?php foreach ($errors as $error): ?>
                            <li><?= htmlspecialchars($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="POST" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

                <div class="mb-4">
                    <label class="form-label">Select Branch</label>
                    <select name="branch" class="form-select" id="single-select-field" style="width: 100%;" required>
                        <option value=""></option>
                        <?php
                        try {
                            $stmt = $conn->prepare("SELECT id, name FROM branch WHERE status = 1 ORDER BY name ASC");
                            $stmt->execute();
                            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                $selected = (isset($_POST['branch']) && $_POST['branch'] == $row['id']) ? 'selected' : '';
                                echo '<option value="'.$row['id'].'" '.$selected.'>'.htmlspecialchars($row['name']).'</option>';
                            }
                        } catch(PDOException $e) {
                            echo '<option disabled>System Unavailable</option>';
                        }
                        ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-control" 
                           value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" 
                           placeholder="Enter username" required>
                </div>

                <div class="mb-2">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" 
                           placeholder="••••••••" required>
                </div>

                <div class="d-flex justify-content-end mb-4">
                    <a onclick="alert('Please contact your technical person to reset your password.')" 
                       class="forgot-password-link">
                        Forgot Password?
                    </a>
                </div>

                <button type="submit" name="submit" class="btn btn-login">
                    Sign In
                </button>

                <div class="text-center mt-3 mb-1 text-muted small">OR</div>

                <a href="super-admin/index.php" class="btn btn-superadmin">
                    Superadmin Login
                </a>

            </form>
        </div>
        
        <div class="copyright">
            &copy; <?= date('Y') ?> Utkal Team Care. All rights reserved.
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#single-select-field').select2({
                theme: "default",
                placeholder: "Search & Select Branch...",
                allowClear: true,
                width: '100%' 
            });
        });
    </script>

</body>
</html>