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

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

// === SECURITY: Must be admin ===
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php'); exit;
}

$success = $error = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add-company'])) {
    $company_name = trim($_POST['site_name'] ?? '');
    $company_email = trim($_POST['company_email'] ?? '');
    $company_address = trim($_POST['company_address'] ?? '');
    $company_phone = trim($_POST['company_phone'] ?? '');

    // Server-side validation
    $valid = true;
    $errors = [];

    if (empty($company_name) || !preg_match("/^[a-zA-Z0-9\s\&\.\-]{2,150}$/", $company_name)) {
        $errors['company_name'] = "Please enter a valid site name.";
        $valid = false;
    }

    if (!filter_var($company_email, FILTER_VALIDATE_EMAIL)) {
        $errors['company_email'] = "Please enter a valid email address.";
        $valid = false;
    }

    if (empty($company_address) || strlen($company_address) < 5) {
        $errors['company_address'] = "Please enter a valid address.";
        $valid = false;
    }

    if (!preg_match("/^\+?\d{10,20}$/", $company_phone)) {
        $errors['company_phone'] = "Please enter a valid phone number.";
        $valid = false;
    }

    if ($valid) {
        try {
            $sql = "INSERT INTO companies (company_name, company_email, company_address, company_phone) 
                    VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssss', $company_name, $company_email, $company_address, $company_phone);
            
            if ($stmt->execute()) {
                $success = "Company added successfully!";
                // Reset form
                $_POST = [];
            } else {
                $error = "Email or phone already exists.";
            }
            $stmt->close();
        } catch (Exception $e) {
            $error = "Database error. Please try again.";
            error_log($e->getMessage());
        }
    } else {
        $error = "Please fix the errors below.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Company</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    :root {
        --primary: #7c3aed;
        --primary-light: #8b5cf6;
        --secondary: #06b6d4;
        --success: #10b981;
        --danger: #ef4444;
        --warning: #f59e0b;
        --dark: #0f172a;
        --darker: #020617;
        --card-bg: rgba(255, 255, 255, 0.08);
        --border: rgba(255, 255, 255, 0.1);
        --text: #f1f5f9;
        --text-light: #cbd5e1;
        --text-lighter: #94a3b8;
        --radius: 1rem;
        --radius-sm: .75rem;
        --transition: all .3s cubic-bezier(.4, 0, .2, 1);
    }

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

    body {
        font-family: 'Inter', sans-serif;
        background: linear-gradient(135deg, var(--darker), var(--dark));
        color: var(--text);
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }

    .background {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        overflow: hidden;
    }

    .gradient-orb {
        position: absolute;
        border-radius: 50%;
        filter: blur(80px);
        opacity: .3;
        animation: float 25s ease-in-out infinite;
    }

    .orb-1 {
        width: 500px;
        height: 500px;
        background: linear-gradient(45deg, var(--primary), var(--secondary));
        top: -200px;
        left: -200px;
    }

    .orb-2 {
        width: 400px;
        height: 400px;
        background: linear-gradient(45deg, var(--secondary), var(--success));
        bottom: -150px;
        right: -150px;
        animation-delay: -8s;
    }

    @keyframes float {

        0%,
        100% {
            transform: translate(0, 0) scale(1);
        }

        25% {
            transform: translate(100px, 100px) scale(1.1);
        }

        50% {
            transform: translate(0, 200px) scale(.9);
        }

        75% {
            transform: translate(-100px, 100px) scale(1.05);
        }
    }

    .form-card {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        width: 100%;
        max-width: 520px;
        padding: 2.5rem;
        box-shadow: 0 20px 40px rgba(0, 0, 0, .3);
        position: relative;
        animation: fadeInUp .6s ease-out;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .form-header {
        text-align: center;
        margin-bottom: 2rem;
    }

    .form-header h1 {
        font-size: 2rem;
        font-weight: 700;
        background: linear-gradient(135deg, var(--text), var(--primary-light));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: .5rem;
    }

    .form-header p {
        color: var(--text-light);
        font-size: .95rem;
    }

    .back-btn {
        position: absolute;
        top: 1.5rem;
        left: 1.5rem;
        background: rgba(255, 255, 255, .1);
        color: var(--text-light);
        border: 1px solid var(--border);
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.1rem;
        cursor: pointer;
        transition: var(--transition);
    }

    .back-btn:hover {
        background: var(--primary);
        color: white;
        border-color: transparent;
        transform: translateY(-2px);
    }

    .alert {
        padding: 1rem 1.25rem;
        border-radius: var(--radius-sm);
        margin-bottom: 1.5rem;
        font-size: .95rem;
        display: flex;
        align-items: center;
        gap: .75rem;
        animation: slideDown .4s ease-out;
    }

    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .alert-success {
        background: rgba(16, 185, 129, .15);
        border: 1px solid rgba(16, 185, 129, .3);
        color: var(--success);
    }

    .alert-error {
        background: rgba(239, 68, 68, .15);
        border: 1px solid rgba(239, 68, 68, .3);
        color: var(--danger);
    }

    .form-group {
        margin-bottom: 1.5rem;
        position: relative;
    }

    .form-label {
        display: block;
        margin-bottom: .5rem;
        color: var(--text-light);
        font-size: .95rem;
        font-weight: 500;
    }

    .form-input {
        width: 100%;
        padding: .875rem 1rem;
        background: rgba(255, 255, 255, .05);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        color: var(--text);
        font-size: .95rem;
        transition: var(--transition);
    }

    .form-input:focus {
        outline: none;
        border-color: var(--primary-light);
        box-shadow: 0 0 0 3px rgba(124, 58, 237, .2);
    }

    .form-input.error {
        border-color: var(--danger);
        box-shadow: 0 0 0 3px rgba(239, 68, 68, .2);
    }

    .field-error {
        color: var(--danger);
        font-size: .8rem;
        margin-top: .5rem;
        display: flex;
        align-items: center;
        gap: .35rem;
        opacity: 0;
        visibility: hidden;
        transition: var(--transition);
    }

    .field-error.show {
        opacity: 1;
        visibility: visible;
    }

    .submit-btn {
        width: 100%;
        padding: 1rem;
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: white;
        border: none;
        border-radius: var(--radius-sm);
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: .75rem;
        transition: var(--transition);
        margin-top: 1rem;
    }

    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(124, 58, 237, .4);
    }

    .submit-btn:disabled {
        opacity: .6;
        cursor: not-allowed;
        transform: none;
    }

    @media (max-width: 480px) {
        .form-card {
            padding: 2rem 1.5rem;
        }

        .form-header h1 {
            font-size: 1.75rem;
        }
    }
    </style>
</head>

<body>

    <div class="background">
        <div class="gradient-orb orb-1"></div>
        <div class="gradient-orb orb-2"></div>
    </div>

    <div class="form-card">
        <a href="company-management.php" class="back-btn" title="Back to Companies">
            Back
        </a>

        <div class="form-header">
            <h1>Add New Company</h1>
            <p>Fill in the details below to register a new company</p>
        </div>

        <?php if ($success): ?>
        <div class="alert alert-success">
            Success: <?= htmlspecialchars($success) ?>
        </div>
        <?php endif; ?>

        <?php if ($error): ?>
        <div class="alert alert-error">
            Error: <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <form action="" method="post" id="companyForm" novalidate>
            <div class="form-group">
                <label for="company_name" class="form-label">Company Name <span class="text-danger">*</span></label>
                <input type="text" name="company_name" id="company_name" class="form-input"
                    value="<?= isset($_POST['company_name']) ? htmlspecialchars($_POST['company_name']) : '' ?>"
                    required>
                <div class="field-error" id="name-error">
                    Error: Please enter a valid name (2-150 chars, letters, numbers, spaces, &, ., -)
                </div>
            </div>

            <div class="form-group">
                <label for="company_email" class="form-label">Email <span class="text-danger">*</span></label>
                <input type="email" name="company_email" id="company_email" class="form-input"
                    value="<?= isset($_POST['company_email']) ? htmlspecialchars($_POST['company_email']) : '' ?>"
                    required>
                <div class="field-error" id="email-error">
                    Error: Please enter a valid email address
                </div>
            </div>

            <div class="form-group">
                <label for="company_address" class="form-label">Address <span class="text-danger">*</span></label>
                <input type="text" name="company_address" id="company_address" class="form-input"
                    value="<?= isset($_POST['company_address']) ? htmlspecialchars($_POST['company_address']) : '' ?>"
                    required>
                <div class="field-error" id="address-error">
                    Error: Address must be at least 5 characters
                </div>
            </div>

            <div class="form-group">
                <label for="company_phone" class="form-label">Phone Number <span class="text-danger">*</span></label>
                <input type="tel" name="company_phone" id="company_phone" class="form-input"
                    value="<?= isset($_POST['company_phone']) ? htmlspecialchars($_POST['company_phone']) : '' ?>"
                    placeholder="+1234567890" required>
                <div class="field-error" id="phone-error">
                    Error: Enter 10-20 digits (optional +)
                </div>
            </div>

            <button type="submit" name="add-company" class="submit-btn" id="submitBtn">
                Add Company
            </button>
        </form>
    </div>

    <script>
    const form = document.getElementById('companyForm');
    const inputs = form.querySelectorAll('.form-input');
    const submitBtn = document.getElementById('submitBtn');

    // Real-time validation
    inputs.forEach(input => {
        input.addEventListener('input', function() {
            validateField(this);
            toggleSubmit();
        });
        input.addEventListener('blur', () => validateField(input));
    });

    function validateField(input) {
        const id = input.id;
        const value = input.value.trim();
        const errorEl = document.getElementById(id + '-error');
        let valid = true;

        switch (id) {
            case 'company_name':
                valid = /^[a-zA-Z0-9\s\&\.\-]{2,150}$/.test(value);
                break;
            case 'company_email':
                valid = /^\S+@\S+\.\S+$/.test(value);
                break;
            case 'company_address':
                valid = value.length >= 5;
                break;
            case 'company_phone':
                valid = /^\+?\d{10,20}$/.test(value);
                break;
        }

        input.classList.toggle('error', !valid);
        errorEl.classList.toggle('show', !valid && value !== '');
        return valid;
    }

    function toggleSubmit() {
        const allValid = Array.from(inputs).every(input => validateField(input));
        submitBtn.disabled = !allValid;
    }

    // Form submit
    form.addEventListener('submit', function(e) {
        let allValid = true;
        inputs.forEach(input => {
            if (!validateField(input)) allValid = false;
        });

        if (!allValid) {
            e.preventDefault();
            submitBtn.disabled = true;
        }
    });

    // Auto-dismiss alerts
    document.querySelectorAll('.alert').forEach(alert => {
        setTimeout(() => {
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 400);
        }, 5000);
    });
    </script>

</body>

</html>