<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

// helper for safe output
function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$lang = $_SESSION['lang'] ?? 'en';
$is_ar = ($lang === 'ar');

$errors = [];
$success = null;

// Handle form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');

    if ($name === '') {
        $errors[] = $is_ar ? "اسم المورد مطلوب" : "Supplier name is required.";
    }

    if (empty($errors)) {
        // prevent duplicate suppliers
        $chk = $pdo->prepare("SELECT COUNT(*) FROM suppliers WHERE name = ?");
        $chk->execute([$name]);
        if ($chk->fetchColumn() > 0) {
            $errors[] = $is_ar ? "اسم المورد موجود مسبقاً" : "Supplier already exists.";
        } else {
            try {
                $ins = $pdo->prepare("INSERT INTO suppliers (name, balance) VALUES (?, 0)");
                $ins->execute([$name]);

                header("Location: suppliers.php?msg=added");
                exit;
            } catch (Exception $e) {
                $errors[] = "DB Error: " . $e->getMessage();
            }
        }
    }
}

?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $is_ar ? "إضافة مورد" : "Add Supplier" ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background:#f5f7fb; font-family: Inter, Arial; padding:20px; }
.card { border-radius:10px; }
</style>
</head>
<body>

<div class="container">
    <div class="d-flex justify-content-between mb-3">
        <h3><?= $is_ar ? "إضافة مورد جديد" : "Add New Supplier" ?></h3>
        <a href="suppliers.php" class="btn btn-outline-secondary"><?= $is_ar ? "رجوع" : "Back" ?></a>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $e) echo esc($e) . "<br>"; ?>
        </div>
    <?php endif; ?>

    <div class="card p-4 shadow-sm">
        <form method="post">
            <div class="mb-3">
                <label class="form-label"><?= $is_ar ? "اسم المورد" : "Supplier Name" ?></label>
                <input type="text" name="name" class="form-control" required>
            </div>

            <button class="btn btn-primary"><?= $is_ar ? "حفظ" : "Save" ?></button>
        </form>
    </div>
</div>

</body>
</html>
