<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}
include '../includes/db.php';

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    header("Location: manage_directors.php");
    exit;
}

$stmt = $conn->prepare("SELECT * FROM directors WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$director = $stmt->get_result()->fetch_assoc();

if (!$director) {
    header("Location: manage_directors.php?msg=not_found");
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_id = intval($_POST['company_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $designation = trim($_POST['designation'] ?? 'Director');
    $director_type = trim($_POST['director_type'] ?? 'Director');
    $short_bio = trim($_POST['short_bio'] ?? '');
    $biography = trim($_POST['biography'] ?? '');
    $education = trim($_POST['education'] ?? '');
    $experience = trim($_POST['experience'] ?? '');
    $linkedin_url = trim($_POST['linkedin_url'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);
    $status = in_array($_POST['status'] ?? '', ['Published', 'Draft', 'Inactive']) ? $_POST['status'] : 'Published';

    if (empty($name)) {
        $error = "Director Name is required.";
    } elseif ($company_id <= 0) {
        $error = "Please select a company.";
    } else {
        $photo_path = $director['photo'];
        $target_dir = "../uploads/directors/";
        if (!is_dir($target_dir)) {
            @mkdir($target_dir, 0777, true);
        }

        $allowed_ext = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, $allowed_ext)) {
                $unique_name = 'director_' . uniqid() . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_dir . $unique_name)) {
                    if (!empty($director['photo']) && file_exists('../' . $director['photo']) && strpos($director['photo'], 'uploads/') === 0) {
                        @unlink('../' . $director['photo']);
                    }
                    $photo_path = 'uploads/directors/' . $unique_name;
                }
            } else {
                $error = "Invalid photo format. Allowed: JPG, PNG, WEBP, GIF.";
            }
        } elseif (!empty($_POST['photo_url'])) {
            $photo_path = trim($_POST['photo_url']);
        }

        if (empty($error)) {
            $upd = $conn->prepare("UPDATE directors SET 
                company_id=?, name=?, photo=?, designation=?, director_type=?, short_bio=?, biography=?,
                education=?, experience=?, linkedin_url=?, display_order=?, status=?
                WHERE id = ?");
            
            $upd->bind_param(
                "isssssssssisi",
                $company_id, $name, $photo_path, $designation, $director_type, $short_bio, $biography,
                $education, $experience, $linkedin_url, $display_order, $status, $id
            );

            if ($upd->execute()) {
                header("Location: manage_directors.php?msg=updated&company_id=" . $company_id);
                exit;
            } else {
                $error = "Database Error: " . $conn->error;
            }
        }
    }
}

// Fetch Companies list
$companies_res = $conn->query("SELECT id, company_name FROM companies ORDER BY company_name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Director - Admin Panel</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="dashboard.css">
    <style>
        .form-section {
            background: #fff;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.06);
        }
        .form-section-title {
            font-size: 16px;
            font-weight: 700;
            color: #1e293b;
            border-bottom: 2px solid #f1f5f9;
            padding-bottom: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .preview-box {
            width: 120px;
            height: 120px;
            border: 2px dashed #cbd5e1;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8fafc;
            margin-top: 10px;
        }
        .preview-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white">
        <a href="dashboard.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
            <span class="fs-4 fw-bold">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a></li>
            <li><a href="manage_services.php"><i class="fas fa-tools me-2"></i> Manage Services</a></li>
            <li><a href="manage_customers.php"><i class="fas fa-building me-2"></i> Manage Companies</a></li>
            <li><a href="manage_founders.php"><i class="fas fa-user-tie me-2"></i> Manage Founders</a></li>
            <li><a href="manage_directors.php" class="active"><i class="fas fa-users-cog me-2"></i> Manage Directors</a></li>
            <li><a href="manage_pages.php"><i class="fas fa-file-alt me-2"></i> Manage Content</a></li>
            <li><a href="manage_blogs.php"><i class="fas fa-blog me-2"></i> Manage Blogs</a></li>
            <li><a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
        </ul>
    </div>

    <div class="content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="mb-0 fw-bold"><i class="fas fa-edit text-primary me-2"></i> Edit Director: <?php echo htmlspecialchars($director['name']); ?></h2>
                <small class="text-muted">Update director profile, governance role, photo, and biographical details</small>
            </div>
            <a href="manage_directors.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to Directors</a>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <form action="director_edit.php?id=<?php echo $id; ?>" method="POST" enctype="multipart/form-data">
            <div class="form-section">
                <div class="form-section-title"><i class="fas fa-user-tie text-primary"></i> Director Details</div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Select Company <span class="text-danger">*</span></label>
                        <select name="company_id" class="form-select" required>
                            <option value="">-- Select Company --</option>
                            <?php if($companies_res): while($comp = $companies_res->fetch_assoc()): ?>
                                <option value="<?php echo $comp['id']; ?>" <?php echo ($director['company_id'] == $comp['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($comp['company_name']); ?>
                                </option>
                            <?php endwhile; endif; ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-bold">Director Full Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($director['name']); ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label fw-bold">Designation</label>
                        <input type="text" name="designation" class="form-control" value="<?php echo htmlspecialchars($director['designation'] ?? 'Director'); ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label fw-bold">Director Type / Role</label>
                        <select name="director_type" class="form-select">
                            <?php 
                            $types = ['Managing Director', 'Executive Director', 'Whole-Time Director', 'Director', 'Non-Executive Director', 'Independent Director', 'Additional Director', 'Nominee Director', 'Technical Director', 'Finance Director'];
                            foreach($types as $t): ?>
                                <option value="<?php echo $t; ?>" <?php echo ($director['director_type'] === $t) ? 'selected' : ''; ?>><?php echo $t; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Experience (Years / Background)</label>
                        <input type="text" name="experience" class="form-control" value="<?php echo htmlspecialchars($director['experience'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Education / Qualifications</label>
                        <input type="text" name="education" class="form-control" value="<?php echo htmlspecialchars($director['education'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">LinkedIn Profile URL</label>
                        <input type="url" name="linkedin_url" class="form-control" value="<?php echo htmlspecialchars($director['linkedin_url'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-bold">Director Photo</label>
                        <input type="file" name="photo" class="form-control" accept="image/*" onchange="previewImage(this, 'photoPreview')">
                        <input type="text" name="photo_url" class="form-control form-control-sm mt-1" placeholder="Or enter existing path / image URL" value="<?php echo (!empty($director['photo']) && strpos($director['photo'], 'http') === 0) ? htmlspecialchars($director['photo']) : ''; ?>">
                        <div class="preview-box" id="photoPreviewBox">
                            <?php if(!empty($director['photo'])): ?>
                                <img id="photoPreview" src="../<?php echo htmlspecialchars($director['photo']); ?>" alt="Photo Preview">
                            <?php else: ?>
                                <img id="photoPreview" src="" style="display:none;" alt="Photo Preview">
                                <span id="photoPlaceholder" class="text-muted small">Photo Preview</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-bold">Display Order</label>
                        <input type="number" name="display_order" class="form-control" value="<?php echo intval($director['display_order']); ?>" min="0">
                        <small class="text-muted">Order priority among directors (0 = 1st, 1 = 2nd)</small>
                        <div class="mt-3">
                            <label class="form-label fw-bold">Publish Status</label>
                            <select name="status" class="form-select">
                                <option value="Published" <?php echo ($director['status'] === 'Published') ? 'selected' : ''; ?>>Published (Publicly Visible)</option>
                                <option value="Draft" <?php echo ($director['status'] === 'Draft') ? 'selected' : ''; ?>>Draft (Hidden)</option>
                                <option value="Inactive" <?php echo ($director['status'] === 'Inactive') ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">Short Bio (Displayed on cards & quick intro)</label>
                        <textarea name="short_bio" class="form-control" rows="2"><?php echo htmlspecialchars($director['short_bio'] ?? ''); ?></textarea>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">Full Biography (Corporate career, key achievements, governance)</label>
                        <textarea name="biography" class="form-control" rows="6"><?php echo htmlspecialchars($director['biography'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>

            <div class="text-end mb-4">
                <button type="submit" class="btn btn-success btn-lg px-4"><i class="fas fa-save me-1"></i> Update Director Profile</button>
            </div>
        </form>
    </div>

    <script>
        function previewImage(input, targetId) {
            const preview = document.getElementById(targetId);
            const placeholder = document.getElementById('photoPlaceholder');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    if (placeholder) placeholder.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
