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

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

$company_id = $_SESSION['company_id'];
$company_user_id = $_SESSION['user_id'];

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

// Get company details
$stmt = $db->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$company_id]);
$company = $stmt->fetch();

// Get current user details
$stmt = $db->prepare("SELECT * FROM company_users WHERE id = ?");
$stmt->execute([$company_user_id]);
$current_user = $stmt->fetch();

if (!$company || !$current_user) {
    redirect('../auth/logout.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    if ($action === 'update_company') {
        // Update company information (only for primary users)
        if ($current_user['is_primary']) {
            $company_name = sanitize($_POST['company_name']);
            $phone = sanitize($_POST['phone']);
            $address = sanitize($_POST['address']);
            $website = sanitize($_POST['website']);
            $description = sanitize($_POST['description']);
            $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']);
            
            if (empty($company_name) || empty($contact_person_name) || empty($contact_person_email)) {
                $error = 'Company name, contact person name and email are required.';
            } else {
                try {
                    // Handle logo upload if provided
                    $logo_filename = $company['logo'];
                    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                        $upload_dir = '../uploads/logos/';
                        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                        $file_type = $_FILES['logo']['type'];
                        
                        if (in_array($file_type, $allowed_types)) {
                            $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)) {
                                // Delete old logo if it exists and is not default
                                if ($company['logo'] && $company['logo'] !== 'default-logo.png' && file_exists($upload_dir . $company['logo'])) {
                                    unlink($upload_dir . $company['logo']);
                                }
                            } else {
                                $error = 'Failed to upload logo.';
                            }
                        } else {
                            $error = 'Logo must be a JPEG, PNG, or GIF image.';
                        }
                    }
                    
                    if (!$error) {
                        $stmt = $db->prepare("
                            UPDATE companies SET 
                                name = ?, phone = ?, address = ?, website = ?, description = ?, logo = ?,
                                contact_person_name = ?, contact_person_email = ?, contact_person_phone = ?, 
                                contact_person_position = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            $company_name, $phone, $address, $website, $description, $logo_filename,
                            $contact_person_name, $contact_person_email, $contact_person_phone, 
                            $contact_person_position, $company_id
                        ]);
                        
                        $success = 'Company profile updated successfully!';
                        
                        // Update session company name
                        $_SESSION['company_name'] = $company_name;
                        
                        // Refresh company data
                        $stmt = $db->prepare("SELECT * FROM companies WHERE id = ?");
                        $stmt->execute([$company_id]);
                        $company = $stmt->fetch();
                    }
                } catch (PDOException $e) {
                    $error = 'Error updating company profile.';
                }
            }
        } else {
            $error = 'Only primary users can update company information.';
        }
    } elseif ($action === 'update_user') {
        // Update current user information
        $name = sanitize($_POST['user_name']);
        $email = sanitize($_POST['user_email']);
        $phone = sanitize($_POST['user_phone']);
        $position = sanitize($_POST['user_position']);
        $password = $_POST['user_password'];
        
        if (empty($name) || empty($email)) {
            $error = 'Name and email are required.';
        } else {
            // Check if email is already used by someone else
            $stmt = $db->prepare("
                SELECT id FROM company_users 
                WHERE email = ? AND id != ?
                UNION
                SELECT id FROM candidates WHERE email = ?
                UNION
                SELECT id FROM admins WHERE email = ?
            ");
            $stmt->execute([$email, $company_user_id, $email, $email]);
            
            if ($stmt->fetch()) {
                $error = 'Email address is already in use.';
            } else {
                try {
                    if (!empty($password)) {
                        // Update with new password
                        if (strlen($password) < 6) {
                            $error = 'Password must be at least 6 characters long.';
                        } else {
                            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                            $stmt = $db->prepare("
                                UPDATE company_users 
                                SET name = ?, email = ?, phone = ?, position = ?, password = ?
                                WHERE id = ?
                            ");
                            $stmt->execute([$name, $email, $phone, $position, $hashed_password, $company_user_id]);
                        }
                    } else {
                        // Update without changing password
                        $stmt = $db->prepare("
                            UPDATE company_users 
                            SET name = ?, email = ?, phone = ?, position = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([$name, $email, $phone, $position, $company_user_id]);
                    }
                    
                    if (!$error) {
                        $success = 'Your profile updated successfully!';
                        
                        // Update session variables
                        $_SESSION['user_email'] = $email;
                        $_SESSION['user_name'] = $name;
                        
                        // Refresh user data
                        $stmt = $db->prepare("SELECT * FROM company_users WHERE id = ?");
                        $stmt->execute([$company_user_id]);
                        $current_user = $stmt->fetch();
                    }
                } catch (PDOException $e) {
                    $error = 'Error updating profile.';
                }
            }
        }
    }
}

// Get all company users
$stmt = $db->prepare("
    SELECT * FROM company_users 
    WHERE company_id = ? 
    ORDER BY is_primary DESC, created_at ASC
");
$stmt->execute([$company_id]);
$company_users = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company Profile - <?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['company_name']); ?>
                </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="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </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="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </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="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-building me-2"></i>Company Profile
                        </h1>
                    </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>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Company Information -->
                        <div class="col-lg-8">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-info-circle me-2"></i>Company Information
                                        <?php if (!$current_user['is_primary']): ?>
                                            <small class="text-muted">(Primary users only)</small>
                                        <?php endif; ?>
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="action" value="update_company">
                                        
                                        <div class="row">
                                            <div class="col-md-8">
                                                <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 htmlspecialchars($company['name']); ?>" 
                                                           <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?> required>
                                                </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 htmlspecialchars($company['phone']); ?>"
                                                           <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>>
                                                </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 htmlspecialchars($company['website']); ?>"
                                                           <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 text-center">
                                                <div class="mb-3">
                                                    <label class="form-label">Company Logo</label>
                                                    <div class="mb-3">
                                                        <?php if ($company['logo']): ?>
                                                            <img src="<?php echo UPLOAD_URL . 'logos/' . $company['logo']; ?>" 
                                                                 alt="Company Logo" class="img-fluid" style="max-width: 150px; max-height: 150px;">
                                                        <?php else: ?>
                                                            <div class="bg-light d-flex align-items-center justify-content-center" 
                                                                 style="width: 150px; height: 150px; margin: 0 auto;">
                                                                <i class="fas fa-building text-muted fa-3x"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php if ($current_user['is_primary']): ?>
                                                        <input type="file" class="form-control" name="logo" accept="image/*">
                                                        <div class="form-text">Upload new logo (optional)</div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="address" class="form-label">Address</label>
                                            <textarea class="form-control" id="address" name="address" rows="3"
                                                      <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>><?php echo htmlspecialchars($company['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"
                                                      <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>><?php echo htmlspecialchars($company['description']); ?></textarea>
                                        </div>
                                        
                                        <hr>
                                        <h6>Contact Person</h6>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_person_name" class="form-label">Name *</label>
                                                <input type="text" class="form-control" id="contact_person_name" name="contact_person_name" 
                                                       value="<?php echo htmlspecialchars($company['contact_person_name']); ?>"
                                                       <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?> required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_person_email" class="form-label">Email *</label>
                                                <input type="email" class="form-control" id="contact_person_email" name="contact_person_email" 
                                                       value="<?php echo htmlspecialchars($company['contact_person_email']); ?>"
                                                       <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?> required>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_person_phone" class="form-label">Phone</label>
                                                <input type="tel" class="form-control" id="contact_person_phone" name="contact_person_phone" 
                                                       value="<?php echo htmlspecialchars($company['contact_person_phone']); ?>"
                                                       <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_person_position" class="form-label">Position</label>
                                                <input type="text" class="form-control" id="contact_person_position" name="contact_person_position" 
                                                       value="<?php echo htmlspecialchars($company['contact_person_position']); ?>"
                                                       <?php echo !$current_user['is_primary'] ? 'readonly' : ''; ?>>
                                            </div>
                                        </div>
                                        
                                        <?php if ($current_user['is_primary']): ?>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-save me-1"></i>Update Company Profile
                                            </button>
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>

                            <!-- User Profile -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-user me-2"></i>My Profile
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <input type="hidden" name="action" value="update_user">
                                        
                                        <div class="row">
                                            <div class="col-md-6 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 htmlspecialchars($current_user['name']); ?>" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="user_email" class="form-label">Email *</label>
                                                <input type="email" class="form-control" id="user_email" name="user_email" 
                                                       value="<?php echo htmlspecialchars($current_user['email']); ?>" required>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="user_phone" class="form-label">Phone</label>
                                                <input type="tel" class="form-control" id="user_phone" name="user_phone" 
                                                       value="<?php echo htmlspecialchars($current_user['phone']); ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="user_position" class="form-label">Position</label>
                                                <input type="text" class="form-control" id="user_position" name="user_position" 
                                                       value="<?php echo htmlspecialchars($current_user['position']); ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="user_password" class="form-label">New Password</label>
                                            <input type="password" class="form-control" id="user_password" name="user_password" 
                                                   placeholder="Leave blank to keep current password">
                                            <div class="form-text">Minimum 6 characters</div>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save me-1"></i>Update My Profile
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Sidebar Info -->
                        <div class="col-lg-4">
                            <!-- Company Users -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-users me-2"></i>Company Users (<?php echo count($company_users); ?>)
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($company_users)): ?>
                                        <p class="text-muted">No users found.</p>
                                    <?php else: ?>
                                        <?php foreach ($company_users as $user): ?>
                                            <div class="d-flex align-items-center mb-3 <?php echo $user['id'] == $company_user_id ? 'border rounded p-2 bg-light' : ''; ?>">
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-0">
                                                        <?php echo htmlspecialchars($user['name']); ?>
                                                        <?php if ($user['is_primary']): ?>
                                                            <span class="badge bg-primary ms-1">Primary</span>
                                                        <?php endif; ?>
                                                        <?php if ($user['id'] == $company_user_id): ?>
                                                            <span class="badge bg-info ms-1">You</span>
                                                        <?php endif; ?>
                                                    </h6>
                                                    <small class="text-muted"><?php echo htmlspecialchars($user['email']); ?></small>
                                                    <?php if ($user['position']): ?>
                                                        <br><small class="text-muted"><?php echo htmlspecialchars($user['position']); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="badge status-<?php echo $user['status']; ?>">
                                                    <?php echo ucfirst($user['status']); ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

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