<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
// Connect to your database
require 'db.php';

// $conn = new mysqli($servername, $username, $password, $dbname);
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Check connection
// if ($conn->connect_error) {
//     $response = [
//         'success' => false,
//         'message' => 'Database connection failed'
//     ];
//     echo json_encode($response);
//     exit;
// }

// Get POST data
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

// Validate input
if (empty($username) || empty($password)) {
    $response = [
        'success' => false,
        'message' => 'Username and password are required'
    ];
    echo json_encode($response);
    exit;
}

// Prepare and execute query
$stmt = $conn->prepare("SELECT user_id, password, role FROM tbl_adhd_users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
    // Verify password (assuming it's hashed with password_hash)
    if ( $password == $user['password'] ) {
        // Password is correct
        $response = [
            'success' => true,
            'message' => 'Login successful',
            'role' => $user['role'],
            'user_id' => $user['user_id']
        ];
    } else {
        // Password is incorrect
        $response = [
            'success' => false,
            'message' => 'Invalid username or password'
        ];
    }
} else {
    // User not found
    $response = [
        'success' => false,
        'message' => 'Invalid username or password'
    ];
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);

// Close connections
$stmt = null;
$conn = null;
?>