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

if (isset($_POST['signin'])) {
    $Email = $_POST['Email'];
    $Password = $_POST['Password'];

    // Validation
    if (empty($Email)) {
        $_SESSION['error'] = 'กรุณากรอกชื่อผู้ใช้งาน';
        header("location: login.php");
        exit;
    } else if (empty($Password)) {
        $_SESSION['error'] = 'กรุณากรอกรหัสผ่าน';
        header("location: login.php");
        exit;
    } else if (strlen($Password) > 20 || strlen($Password) < 8) {
        $_SESSION['error'] = 'รหัสผ่านต้องมีความยาวระหว่าง 8-20 ตัวอักษร';
        header("location: login.php");
        exit;
    } else {
        try {
            $check_data = $conn->prepare("SELECT * FROM customer WHERE Email = :Email");
            $check_data->bindParam(":Email", $Email);
            $check_data->execute();
            $row = $check_data->fetch(PDO::FETCH_ASSOC);

            if ($check_data->rowCount() > 0) {
                if (password_verify($Password, $row['Password'])) {
                    if ($row['Level'] == 'Admin') {
                        $_SESSION['admin_login'] = $row['Customer_ID'];
                        header("location: index.php"); // Redirect to index.php
                        exit;
                    } else if ($row['Level'] == 'SuperAdmin') {
                        $_SESSION['superadmin_login'] = $row['Customer_ID'];
                        header("location: index.php"); // Redirect to index.php
                        exit;
                    } else if ($row['Level'] == 'Consult') {
                        $_SESSION['consult_login'] = $row['Customer_ID'];
                        header("location: indexUser.php"); // Redirect to index.php
                        exit;
                    } else if ($row['Level'] == 'User') {
                        $_SESSION['user_login'] = $row['Customer_ID'];
                        header("location: indexUser.php"); // Redirect to indexUser.php
                        exit;
                    }
                } else {
                    $_SESSION['error'] = 'รหัสผ่านผิด';
                    header("location: login.php");
                    exit;
                }
            } else {
                $_SESSION['error'] = 'ไม่มีข้อมูลในระบบ';
                header("location: login.php");
                exit;
            }
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
}
?>
