<?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();
}

$success = "";
$error = "";

// Generate Offer Code (OFR-001, OFR-002...)
function generateOfferCode(mysqli $conn): string {
    $sql = "SELECT offer_code FROM offer_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['offer_code'], 4) + 1;
    }
    return sprintf("OFR-%03d", $next);
}

$generated_code = generateOfferCode($conn);

// Fetch Enquiries for reference (Optional)
$enquiries = $conn->query("SELECT id, enquiry_code, name, mobile FROM enquiry_master 
                          WHERE status = 'Active' ORDER BY enquiry_date DESC");

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $offer_code      = $generated_code;
    $offer_date      = $_POST['offer_date'] ?? date('Y-m-d');
    $enquiry_id      = !empty($_POST['enquiry_id']) ? (int)$_POST['enquiry_id'] : null;
    $customer_name   = trim($_POST['customer_name'] ?? '');
    $mobile          = trim($_POST['mobile'] ?? '');
    $address         = trim($_POST['address'] ?? '');
    $valid_until     = $_POST['valid_until'] ?? date('Y-m-d', strtotime('+30 days'));
    $status          = $_POST['status'] ?? 'Pending';
    $remarks         = trim($_POST['remarks'] ?? '');

    if (empty($customer_name) || empty($mobile)) {
        $error = "Customer Name and Mobile are required.";
    } else {
        try {
            $stmt = $conn->prepare("
                INSERT INTO offer_master (
                    offer_code, offer_date, enquiry_id, customer_name, mobile, 
                    address, valid_until, status, remarks, created_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $stmt->bind_param("ssissssssi",
                $offer_code, $offer_date, $enquiry_id, $customer_name, $mobile,
                $address, $valid_until, $status, $remarks, $_SESSION['user_id']
            );

            if ($stmt->execute()) {
                $success = "Offer created successfully!";
                header("Location: offer-management.php?success=1");
                exit();
            } else {
                $error = "Failed to create offer.";
            }
        } catch (Exception $e) {
            $error = "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>Create New Offer</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: 780px; 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; }

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

        input, select, textarea {
            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, textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
        }
        option{
            color: black;
        }
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        .submit-btn {
            width: 100%;
            padding: 19px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 1.15rem;
            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="offer-management.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to Offers
            </a>
            <h1><i class="fas fa-file-invoice"></i> Create New Offer</h1>
            <p style="margin-top:12px; opacity:0.9;">Generate quotation / offer</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" autocomplete="off">

                <div class="form-grid">
                    <div class="form-group">
                        <label>Offer Code <span class="required">*</span></label>
                        <input type="text" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                    </div>
                    <div class="form-group">
                        <label>Offer Date <span class="required">*</span></label>
                        <input type="date" name="offer_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>Linked Enquiry (Optional)</label>
                    <select name="enquiry_id">
                        <option value="">Direct Offer (No Enquiry)</option>
                        <?php while ($enq = $enquiries->fetch_assoc()): ?>
                            <option value="<?= $enq['id'] ?>">
                                <?= htmlspecialchars($enq['enquiry_code']) ?> - <?= htmlspecialchars($enq['name']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Customer Name <span class="required">*</span></label>
                        <input type="text" name="customer_name" required placeholder="Full customer name">
                    </div>
                    <div class="form-group">
                        <label>Mobile Number <span class="required">*</span></label>
                        <input type="text" name="mobile" required placeholder="Mobile number">
                    </div>
                </div>

                <div class="form-group">
                    <label>Address</label>
                    <textarea name="address" rows="2" placeholder="Full address"></textarea>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Valid Until</label>
                        <input type="date" name="valid_until" value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status">
                            <option value="Pending">Pending</option>
                            <option value="Sent">Sent</option>
                            <option value="Accepted">Accepted</option>
                            <option value="Rejected">Rejected</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label>Remarks / Terms & Conditions</label>
                    <textarea name="remarks" rows="4" placeholder="Payment terms, validity, notes..."></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-file-invoice"></i> Create Offer
                </button>
            </form>
        </div>
    </div>
</div>

</body>
</html>

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