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

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

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

$company = null;
$error = $success = '';

// Check ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: company-management.php");
    exit;
}
$id = (int)$_GET['id'];

// Load company
$sql = "SELECT * FROM companies WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $error = "Company not found.";
} else {
    $company = $result->fetch_assoc();
}
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $company_email = trim($_POST['company_email'] ?? '');
    $company_address = trim($_POST['company_address'] ?? '');
    $company_phone = trim($_POST['company_phone'] ?? '');

    $valid = true;
    $errors = [];

    // Validation
    if (empty($company_name) || !preg_match("/^[a-zA-Z0-9\s\&\.\-]{2,150}$/", $company_name)) {
        $errors['company_name'] = "Valid company name required (2–150 chars).";
        $valid = false;
    }

    if (!filter_var($company_email, FILTER_VALIDATE_EMAIL)) {
        $errors['company_email'] = "Valid email required.";
        $valid = false;
    }

    if (strlen($company_address) < 5) {
        $errors['company_address'] = "Address must be at least 5 characters.";
        $valid = false;
    }

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

    // Check email uniqueness (exclude current company)
    if ($valid && $company_email !== $company['company_email']) {
        $check = $conn->prepare("SELECT id FROM companies WHERE company_email = ? AND id != ?");
        $check->bind_param('si', $company_email, $id);
        $check->execute();
        $check->store_result();
        if ($check->num_rows > 0) {
            $errors['company_email'] = "This email is already in use.";
            $valid = false;
        }
        $check->close();
    }

    if ($valid) {
        $update = $conn->prepare("UPDATE companies SET company_name = ?, company_email = ?, company_address = ?, company_phone = ? WHERE id = ?");
        $update->bind_param('ssssi', $company_name, $company_email, $company_address, $company_phone, $id);
        
        if ($update->execute()) {
            $success = "Company updated successfully!";
            // Refresh data
            $company['company_name'] = $company_name;
            $company['company_email'] = $company_email;
            $company['company_address'] = $company_address;
            $company['company_phone'] = $company_phone;
        } else {
            $error = "Update failed. Please try again.";
        }
        $update->close();
    } 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>Edit 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);
            text-decoration: none;
        }
        .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,
        .form-textarea {
            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);
            resize: vertical;
        }
        .form-input:focus,
        .form-textarea:focus {
            outline: none;
            border-color: var(--primary-light);
            box-shadow: 0 0 0 3px rgba(124,58,237,.2);
        }
        .form-input.error,
        .form-textarea.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;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 1.5rem;
        }
        .btn {
            padding: .75rem 1.5rem;
            border: none;
            border-radius: var(--radius-sm);
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: .5rem;
            text-decoration: none;
            font-size: .95rem;
        }
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
        }
        .btn-secondary {
            background: var(--card-bg);
            color: var(--text-light);
            border: 1px solid var(--border);
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0,0,0,.3);
        }
        .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; }
            .form-actions { flex-direction: column; }
            .btn { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>

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

<?php if (!$company && $error): ?>
<div class="form-card">
    <div class="form-header">
        <h1>Error</h1>
    </div>
    <div class="alert alert-error">
        Error: <?= htmlspecialchars($error) ?>
    </div>
    <div class="form-actions">
        <a href="company-management.php" class="btn btn-secondary">
            Back to Companies
        </a>
    </div>
</div>

<?php elseif ($company): ?>
<div class="form-card">
    <a href="company-management.php" class="back-btn" title="Back to Companies">
        Back
    </a>

    <div class="form-header">
        <h1>Edit Company</h1>
        <p>Update the company details below</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 method="post" id="editForm" 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="<?= htmlspecialchars($company['company_name']) ?>" required>
            <div class="field-error" id="name-error">
                Error: 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="<?= htmlspecialchars($company['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>
            <textarea name="company_address" id="company_address" class="form-textarea" rows="3" required><?= htmlspecialchars($company['company_address']) ?></textarea>
            <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="<?= htmlspecialchars($company['company_phone']) ?>" placeholder="+1234567890" required>
            <div class="field-error" id="phone-error">
                Error: Enter 10-20 digits (optional +)
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary" id="submitBtn">
                Save Changes
            </button>
            <a href="view-company.php?id=<?= $id ?>" class="btn btn-secondary">
                Cancel
            </a>
        </div>
    </form>
</div>
<?php endif; ?>

<script>
    const form = document.getElementById('editForm');
    const inputs = form?.querySelectorAll('.form-input, .form-textarea');
    const submitBtn = document.getElementById('submitBtn');

    if (form) {
        // 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>