<?php
// login.php — Backend authentication handler for signin.php
//
// signin.php (the "Log Into Your Account" screen) POSTs here with:
//   identifier — the user's email address OR phone number
//   password   — plain-text password
//   redirect   — optional internal path to send the user back to
//
// On failure: stores a message in $_SESSION['login_error'] and redirects
// back to signin.php (which renders the error banner).
// On success: starts the customer session and redirects to dashboard.php
// (or the requested $redirect target), and sets a long-lived
// "dabil_returning" cookie so splash.php can route returning users
// straight to signin.php instead of the onboarding screens.

session_start();
require_once __DIR__ . '/config/db.php';

/**
 * Only allow redirecting to a relative, same-site path. Prevents this
 * handler from being used as an open redirect via ?redirect=.
 */
function dabil_safe_redirect(string $path): string
{
    $path = trim($path);
    if ($path === '') {
        return 'dashboard.php';
    }
    // Reject absolute / protocol-relative URLs and path traversal tricks.
    if (preg_match('#^([a-z][a-z0-9+.-]*:)?//#i', $path) || str_starts_with($path, '\\')) {
        return 'dashboard.php';
    }
    return $path;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: signin.php');
    exit;
}

$identifier = trim($_POST['identifier'] ?? '');
$password   = (string) ($_POST['password'] ?? '');
$redirect   = dabil_safe_redirect($_POST['redirect'] ?? '');

if ($identifier === '' || $password === '') {
    $_SESSION['login_error'] = 'Please fill in all fields.';
    header('Location: signin.php');
    exit;
}

// Look up by email or phone — both are accepted in the "Email ID / Phone
// Number" field on signin.php.
$stmt = $conn->prepare(
    // Organisation staff (org_staff) also use the customer app to spend their
    // meal-ticket / wallet balance, so they're allowed to sign in here too.
    "SELECT id, name, email, phone, password, role, status
     FROM users
     WHERE (email = ? OR phone = ?) AND role IN ('customer','org_staff')
     LIMIT 1"
);
$stmt->bind_param('ss', $identifier, $identifier);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user || !password_verify($password, $user['password'])) {
    $_SESSION['login_error'] = 'Invalid email/phone or password. Please try again.';
    header('Location: signin.php');
    exit;
}

if ((int) $user['status'] !== 1) {
    $_SESSION['login_error'] = 'Your account is inactive. Please contact support.';
    header('Location: signin.php');
    exit;
}

// --- Success: start the session ---
session_regenerate_id(true);
$_SESSION['user_id']    = (int) $user['id'];
$_SESSION['user_name']  = $user['name'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['role']       = $user['role'];

unset($_SESSION['login_error'], $_SESSION['login_redirect']);

// Returning-user cookie: lets splash.php skip the onboarding screens
// (welcome/order/manage) and send the user straight to signin.php next time.
setcookie('dabil_returning', '1', [
    'expires'  => time() + 60 * 60 * 24 * 365,
    'path'     => '/',
    'secure'   => !empty($_SERVER['HTTPS']),
    'httponly' => true,
    'samesite' => 'Lax',
]);

header('Location: ' . $redirect);
exit;
