<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

// Allowed roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

// Generate Vendor Code
function generateVendorCode(mysqli $conn): string {
    $sql = "SELECT vendor_code FROM vendor_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['vendor_code'], 3) + 1;
    }
    return sprintf("VE-%02d", $next);
}

$success = "";
$error = "";
$generated_code = generateVendorCode($conn);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Your existing POST logic (kept unchanged for safety)
    $vendor_code         = trim($_POST["vendor_code"]);
    $vendor_name         = trim($_POST["vendor_name"]);
    $vendor_address      = trim($_POST["vendor_address"]);
    $vendor_contact      = trim($_POST["vendor_contact"]);
    $vendor_email        = trim($_POST["vendor_email"]);
    $gst_number          = trim($_POST["gst_number"]);
    $pan_number          = trim($_POST["pan_number"]);
    $vendor_status       = $_POST["vendor_status"] ?? 'Active';
    $vendor_payment_term = trim($_POST["vendor_payment_term"]);
    $vendor_category     = $_POST["vendor_category"];

    if (empty($vendor_name)) {
        $error = "Vendor Name is required.";
    } elseif (empty($vendor_category)) {
        $error = "Vendor Category is required.";
    } elseif (!empty($vendor_email) && !filter_var($vendor_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        try {
            $query = "INSERT INTO vendor_master (
                vendor_code, vendor_name, vendor_address, vendor_contact, 
                vendor_email, vendor_status, vendor_payment_term, vendor_category, 
                gst_number, pan_number
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($query);
            $stmt->bind_param("ssssssssss",
                $vendor_code, $vendor_name, $vendor_address, $vendor_contact,
                $vendor_email, $vendor_status, $vendor_payment_term, $vendor_category,
                $gst_number, $pan_number
            );

            if ($stmt->execute()) {
                $success = "Vendor added successfully!";
                header("Location: vendor-management.php?success=1");
                exit();
            } else {
                $error = "Failed to add vendor.";
            }
        } catch (Exception $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Vendor</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }

        * { margin:0; padding:0; box-sizing:border-box; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), 
                        url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }

        .container { max-width: 720px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 700;
        }

        .form-area { padding: 45px 40px; }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin-bottom: 30px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .success { background: rgba(34,197,94,0.25); border: 1px solid #4ade80; color: #86efac; }
        .error   { background: rgba(239,68,68,0.25); border: 1px solid #f87171; color: #fca5a5; }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #e0e7ff;
        }
        .required { color: #f87171; }

        input, select {
            width: 100%;
            padding: 14px 18px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }

        input:focus, select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
        }

        input[readonly] {
            background: rgba(255,255,255,0.08);
            cursor: not-allowed;
        }

        .submit-btn {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 1.2rem;
            font-weight: 700;
            cursor: pointer;
            margin-top: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .submit-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 20px 50px rgba(168,85,247,0.5);
        }

        @media (max-width: 640px) {
            .glass-container { border-radius: 24px; }
            .header, .form-area { padding: 35px 25px; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <div class="header">
            <a href="vendor-management.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to Vendors
            </a>
            <h1><i class="fas fa-user-tie"></i> Add New Vendor</h1>
            <p style="margin-top:12px; opacity:0.9;">Register a new supplier</p>
        </div>

        <div class="form-area">
            <?php if ($success): ?>
                <div class="message success">
                    <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="message error">
                    <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="post">

                <div class="form-grid">
                    <div class="form-group">
                        <label>Vendor Code <span class="required">*</span></label>
                        <input type="text" name="vendor_code" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                    </div>

                    <div class="form-group">
                        <label>Vendor Name <span class="required">*</span></label>
                        <input type="text" name="vendor_name" value="<?= htmlspecialchars($_POST['vendor_name'] ?? '') ?>" required placeholder="Full vendor name">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" name="vendor_address" value="<?= htmlspecialchars($_POST['vendor_address'] ?? '') ?>" placeholder="Complete address">
                    </div>
                    <div class="form-group">
                        <label>Contact Number</label>
                        <input type="text" name="vendor_contact" value="<?= htmlspecialchars($_POST['vendor_contact'] ?? '') ?>" placeholder="Phone / Mobile">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" name="vendor_email" value="<?= htmlspecialchars($_POST['vendor_email'] ?? '') ?>" placeholder="vendor@example.com">
                    </div>
                    <div class="form-group">
                        <label>GST Number</label>
                        <input type="text" name="gst_number" value="<?= htmlspecialchars($_POST['gst_number'] ?? '') ?>" placeholder="GSTIN">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>PAN Number</label>
                        <input type="text" name="pan_number" value="<?= htmlspecialchars($_POST['pan_number'] ?? '') ?>" placeholder="PAN Number">
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="vendor_status">
                            <option value="Active" <?= ($_POST['vendor_status'] ?? 'Active') === 'Active' ? 'selected' : '' ?>>Active</option>
                            <option value="Inactive" <?= ($_POST['vendor_status'] ?? '') === 'Inactive' ? 'selected' : '' ?>>Inactive</option>
                        </select>
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Payment Terms</label>
                        <input type="text" name="vendor_payment_term" value="<?= htmlspecialchars($_POST['vendor_payment_term'] ?? '') ?>" placeholder="Net 30, COD, etc.">
                    </div>
                    <div class="form-group">
                        <label>Category <span class="required">*</span></label>
                        <select name="vendor_category" required>
                            <option value="">Select Category</option>
                            <option value="EQP" <?= ($_POST['vendor_category'] ?? '') === 'EQP' ? 'selected' : '' ?>>EQP (Equipment)</option>
                            <option value="LOW-ANS" <?= ($_POST['vendor_category'] ?? '') === 'LOW-ANS' ? 'selected' : '' ?>>LOW-ANS (Low Value)</option>
                            <option value="VEN" <?= ($_POST['vendor_category'] ?? '') === 'VEN' ? 'selected' : '' ?>>VEN (General Vendor)</option>
                        </select>
                    </div>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-plus"></i> Add Vendor
                </button>
            </form>
        </div>
    </div>
</div>

</body>
</html>

<?php $conn->close(); ?>