<?php
require_once '../config/config.php';
requireLogin('admin');

$database = new Database();
$db = $database->getConnection();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = sanitize($_POST['company_name']);
    $phone = sanitize($_POST['phone']);
    $address = sanitize($_POST['address']);
    $website = sanitize($_POST['website']);
    $description = sanitize($_POST['description']);
    $status = $_POST['status'];
    
    // Contact person details
    $contact_person_name = sanitize($_POST['contact_person_name']);
    $contact_person_email = sanitize($_POST['contact_person_email']);
    $contact_person_phone = sanitize($_POST['contact_person_phone']);
    $contact_person_position = sanitize($_POST['contact_person_position']);
    
    // Primary user details
    $user_name = sanitize($_POST['user_name']);
    $user_email = sanitize($_POST['user_email']);
    $user_password = $_POST['user_password'];
    $user_phone = sanitize($_POST['user_phone']);
    $user_position = sanitize($_POST['user_position']);
    
    // Validation
    if (empty($company_name) || empty($contact_person_name) || empty($contact_person_email) || 
        empty($user_name) || empty($user_email) || empty($user_password)) {
        $error = 'Company name, contact person details, and primary user details are required.';
    } elseif (strlen($user_password) < 6) {
        $error = 'User password must be at least 6 characters long.';
    } elseif (!isset($_FILES['logo']) || $_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Company logo is required.';
    } else {
        // Check if emails already exist
        $check_tables = [
            ['table' => 'companies', 'email_field' => 'contact_person_email'],
            ['table' => 'company_users', 'email_field' => 'email'],
            ['table' => 'candidates', 'email_field' => 'email'],
            ['table' => 'admins', 'email_field' => 'email']
        ];
        
        $email_exists = false;
        $emails_to_check = [$contact_person_email, $user_email];
        
        foreach ($emails_to_check as $email) {
            foreach ($check_tables as $check) {
                $stmt = $db->prepare("SELECT id FROM {$check['table']} WHERE {$check['email_field']} = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $email_exists = true;
                    break 2;
                }
            }
        }
        
        if ($email_exists) {
            $error = 'One of the email addresses is already registered.';
        } else {
            // Handle logo upload
            $logo_filename = '';
            $upload_dir = '../uploads/logos/';
            $upload_path = '';
            
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
            $file_type = $_FILES['logo']['type'];
            
            if (!in_array($file_type, $allowed_types)) {
                $error = 'Logo must be a JPEG, PNG, or GIF image.';
            } else {
                $file_extension = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                $logo_filename = uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $logo_filename;
                
                if (!move_uploaded_file($_FILES['logo']['tmp_name'], $upload_path)) {
                    $error = 'Failed to upload logo. Please try again.';
                }
            }
            
            if (!$error) {
                try {
                    $db->beginTransaction();
                    
                    // Insert company
                    $stmt = $db->prepare("
                        INSERT INTO companies (name, email, password, phone, address, website, description, logo, 
                                             contact_person_name, contact_person_email, contact_person_phone, 
                                             contact_person_position, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    // Use a default password since companies authenticate through company_users
                    $default_company_password = password_hash('company_default_' . uniqid(), PASSWORD_DEFAULT);
                    $stmt->execute([
                        $company_name, $contact_person_email, $default_company_password, $phone, $address, 
                        $website, $description, $logo_filename, $contact_person_name, $contact_person_email, 
                        $contact_person_phone, $contact_person_position, $status
                    ]);
                    
                    $company_id = $db->lastInsertId();
                    
                    // Insert primary user
                    $hashed_password = password_hash($user_password, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("
                        INSERT INTO company_users (company_id, name, email, password, phone, position, is_primary) 
                        VALUES (?, ?, ?, ?, ?, ?, 1)
                    ");
                    $stmt->execute([
                        $company_id, $user_name, $user_email, $hashed_password, $user_phone, $user_position
                    ]);
                    
                    $db->commit();
                    $success = 'Company and primary user added successfully!';
                    
                    // Clear form data on success
                    $_POST = [];
                    
                } catch (PDOException $e) {
                    $db->rollBack();
                    if (!empty($upload_path) && file_exists($upload_path)) {
                        unlink($upload_path);
                    }
                    
                    // Log the actual error for debugging
                    error_log("Company addition error: " . $e->getMessage());
                    
                    // Show specific error messages for common issues
                    $error_message = $e->getMessage();
                    if (strpos($error_message, 'Duplicate entry') !== false) {
                        if (strpos($error_message, 'contact_person_email') !== false) {
                            $error = 'Contact person email already exists in the system.';
                        } elseif (strpos($error_message, 'companies.name') !== false) {
                            $error = 'A company with this name already exists.';
                        } else {
                            $error = 'Duplicate entry detected. Please check your data.';
                        }
                    } elseif (strpos($error_message, "doesn't exist") !== false) {
                        $error = 'Database table error. Please contact the administrator.';
                    } elseif (strpos($error_message, 'Data too long') !== false) {
                        $error = 'One or more fields contain too much data. Please shorten your entries.';
                    } elseif (strpos($error_message, 'cannot be null') !== false) {
                        $error = 'Required database field is missing. Please fill all required fields.';
                    } else {
                        // For development/debugging, show the actual error
                        // In production, you might want to show a generic message
                        $error = 'Database error: ' . $error_message;
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Company - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="companies.php">
                                <i class="fas fa-building me-2"></i>Manage Companies
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="candidates.php">
                                <i class="fas fa-users me-2"></i>Manage Candidates
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="categories.php">
                                <i class="fas fa-tags me-2"></i>Job Categories
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="admin-users.php">
                                <i class="fas fa-user-shield me-2"></i>Admin Users
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <!-- Breadcrumb -->
                    <nav aria-label="breadcrumb" class="mb-4">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="companies.php">Companies</a></li>
                            <li class="breadcrumb-item active">Add Company</li>
                        </ol>
                    </nav>

                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-plus-circle me-2"></i>Add New Company
                        </h1>
                        <a href="companies.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Back to Companies
                        </a>
                    </div>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            <div class="mt-2">
                                <a href="companies.php" class="btn btn-success btn-sm me-2">View All Companies</a>
                                <a href="add-company.php" class="btn btn-outline-success btn-sm">Add Another Company</a>
                            </div>
                        </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="row">
                            <!-- Company Information -->
                            <div class="col-lg-6 mb-4">
                                <div class="card h-100">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fas fa-building me-2"></i>Company Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="company_name" class="form-label">Company Name *</label>
                                            <input type="text" class="form-control" id="company_name" name="company_name" 
                                                   value="<?php echo isset($_POST['company_name']) ? htmlspecialchars($_POST['company_name']) : ''; ?>" 
                                                   required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="logo" class="form-label">Company Logo *</label>
                                            <input type="file" class="form-control" id="logo" name="logo" 
                                                   accept="image/jpeg,image/png,image/gif" required>
                                            <div class="form-text">Upload company logo (JPEG, PNG, or GIF)</div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="phone" class="form-label">Company Phone</label>
                                            <input type="tel" class="form-control" id="phone" name="phone" 
                                                   value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label for="website" class="form-label">Website</label>
                                            <input type="url" class="form-control" id="website" name="website" 
                                                   value="<?php echo isset($_POST['website']) ? htmlspecialchars($_POST['website']) : ''; ?>" 
                                                   placeholder="https://example.com">
                                        </div>

                                        <div class="mb-3">
                                            <label for="status" class="form-label">Account Status *</label>
                                            <select class="form-select" id="status" name="status" required>
                                                <option value="approved" <?php echo (isset($_POST['status']) && $_POST['status'] === 'approved') ? 'selected' : ''; ?>>Approved</option>
                                                <option value="pending" <?php echo (isset($_POST['status']) && $_POST['status'] === 'pending') ? 'selected' : ''; ?>>Pending</option>
                                                <option value="rejected" <?php echo (isset($_POST['status']) && $_POST['status'] === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <label for="address" class="form-label">Company Address</label>
                                            <textarea class="form-control" id="address" name="address" rows="3" 
                                                      placeholder="Full company address"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label for="description" class="form-label">Company Description</label>
                                            <textarea class="form-control" id="description" name="description" rows="4" 
                                                      placeholder="Brief description about the company..."><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Contact Person & Primary User -->
                            <div class="col-lg-6">
                                <!-- Contact Person -->
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fas fa-user-tie me-2"></i>Contact Person
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="contact_person_name" class="form-label">Full Name *</label>
                                            <input type="text" class="form-control" id="contact_person_name" name="contact_person_name" 
                                                   value="<?php echo isset($_POST['contact_person_name']) ? htmlspecialchars($_POST['contact_person_name']) : ''; ?>" 
                                                   required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="contact_person_email" class="form-label">Email Address *</label>
                                            <input type="email" class="form-control" id="contact_person_email" name="contact_person_email" 
                                                   value="<?php echo isset($_POST['contact_person_email']) ? htmlspecialchars($_POST['contact_person_email']) : ''; ?>" 
                                                   required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="contact_person_phone" class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" id="contact_person_phone" name="contact_person_phone" 
                                                   value="<?php echo isset($_POST['contact_person_phone']) ? htmlspecialchars($_POST['contact_person_phone']) : ''; ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label for="contact_person_position" class="form-label">Position/Title</label>
                                            <input type="text" class="form-control" id="contact_person_position" name="contact_person_position" 
                                                   value="<?php echo isset($_POST['contact_person_position']) ? htmlspecialchars($_POST['contact_person_position']) : ''; ?>" 
                                                   placeholder="e.g., HR Manager, CEO">
                                        </div>
                                    </div>
                                </div>

                                <!-- Primary User Account -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="fas fa-user-plus me-2"></i>Primary User Account
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="user_name" class="form-label">Full Name *</label>
                                            <input type="text" class="form-control" id="user_name" name="user_name" 
                                                   value="<?php echo isset($_POST['user_name']) ? htmlspecialchars($_POST['user_name']) : ''; ?>" 
                                                   required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="user_email" class="form-label">Email Address *</label>
                                            <input type="email" class="form-control" id="user_email" name="user_email" 
                                                   value="<?php echo isset($_POST['user_email']) ? htmlspecialchars($_POST['user_email']) : ''; ?>" 
                                                   required>
                                            <div class="form-text">This will be used to login to the system</div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="user_password" class="form-label">Password *</label>
                                            <input type="password" class="form-control" id="user_password" name="user_password" 
                                                   placeholder="Minimum 6 characters" required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="user_phone" class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" id="user_phone" name="user_phone" 
                                                   value="<?php echo isset($_POST['user_phone']) ? htmlspecialchars($_POST['user_phone']) : ''; ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label for="user_position" class="form-label">Position/Title</label>
                                            <input type="text" class="form-control" id="user_position" name="user_position" 
                                                   value="<?php echo isset($_POST['user_position']) ? htmlspecialchars($_POST['user_position']) : ''; ?>" 
                                                   placeholder="e.g., HR Manager, Recruiter">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-plus me-1"></i>Add Company & User
                                    </button>
                                    <a href="companies.php" class="btn btn-outline-secondary">Cancel</a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>