<?php
session_start();

header("Content-Type: application/json");

$localhost = 'localhost';
$user = 'netsafc2_adds';
$pass = '@mashaAllah01';
$dbn = "netsafc2_inyass";

// Create connection
$conn = new mysqli($localhost, $user, $pass, $dbn);

// Check connection
if ($conn->connect_error) {
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Prepare statement to prevent SQL injection
    $stmt = $conn->prepare("SELECT id, password_hash FROM `61685008ce` WHERE username = ?");
    
    if (!$stmt) {
        echo json_encode(["status" => "error", "message" => "Database error: " . $conn->error]);
        exit();
    }

    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password_hash);
        $stmt->fetch();

        // Verify password
        if (password_verify($password, $password_hash)) {
            $_SESSION['admin_id'] = $id;
            $_SESSION['username'] = $username;

            echo json_encode(["status" => "success"]);
            exit();
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
            exit();
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
        exit();
    }

    $stmt->close();
}

$conn->close();
?>
