<?php
require_once __DIR__ . '/config/config.php';

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');

    if (strlen($password) < 10 || !preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/[0-9]/', $password) || !preg_match('/[^A-Za-z0-9]/', $password)) {
        $error = 'Password must be at least 10 characters and include uppercase, lowercase, number, and special character.';
    } else {
        $check = db()->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
        $check->execute([$username]);
        if ($check->fetch()) {
            $error = 'Username already exists.';
        } else {
            $stmt = db()->prepare("INSERT INTO users (full_name, username, password_hash, role, account_type, phone, address, portal_access, status, password_changed_at, password_expires_at, created_at) VALUES (?, ?, ?, 'admin', 'internal', ?, ?, 'admin', 'active', NOW(), DATE_ADD(NOW(), INTERVAL 90 DAY), NOW())");
            $stmt->execute([
                $fullName,
                $username,
                password_hash($password, PASSWORD_DEFAULT),
                $phone,
                $address
            ]);
            $message = 'Admin account created successfully. Remove or protect this file after first use.';
        }
    }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Create Admin - SHAHANA VEGETABLES</title>
  <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="login-shell">
  <div class="login-card">
    <div class="hero-pane">
      <h1>Create First Admin</h1>
      <p>Use this page once to create the first administrator for SHAHANA VEGETABLES. Delete or password-protect this file after creating the account.</p>
    </div>
    <div class="form-pane">
      <h2>Admin Setup</h2>
      <?php if ($message): ?><p style="color:#215f24"><?php echo htmlspecialchars($message); ?></p><?php endif; ?>
      <?php if ($error): ?><p style="color:#b23b3b"><?php echo htmlspecialchars($error); ?></p><?php endif; ?>
      <form method="post">
        <label>Full Name</label>
        <input type="text" name="full_name" required>
        <label>Username</label>
        <input type="text" name="username" required>
        <label>Phone</label>
        <input type="text" name="phone">
        <label>Address</label>
        <textarea name="address" rows="3"></textarea>
        <label>Secure Password</label>
        <input type="password" name="password" required>
        <button class="btn btn-primary" type="submit">Create Admin</button>
      </form>
    </div>
  </div>
</div>
</body>
</html>
