<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Handle CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("POST Data: " . print_r($_POST, true));
    error_log("FILES Data: " . print_r($_FILES, true));

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $name = trim($_POST['name']);
        $role = trim($_POST['role']);
        $bio = trim($_POST['bio']);
        $location = trim($_POST['location']);
        $is_ceo = isset($_POST['is_ceo']) ? 1 : 0;
        
        // Handle image upload
        $image_path = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = $_FILES['image']['type'];
            
            if (in_array($file_type, $allowed_types)) {
                $upload_dir = 'assets/img/team/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $file_name = 'team_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
                    $image_path = $file_path;
                }
            }
        }

        $stmt = $pdo->prepare("INSERT INTO team_members (name, role, bio, location, image_path, is_ceo, status) VALUES (?, ?, ?, ?, ?, ?, 'active')");
        if ($stmt->execute([$name, $role, $bio, $location, $image_path, $is_ceo])) {
            $_SESSION['flash'] = ['message'=>'Team member added successfully!','color'=>'#28a745'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to add team member.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        $id = intval($_POST['id']);
        $name = trim($_POST['name']);
        $role = trim($_POST['role']);
        $bio = trim($_POST['bio']);
        $location = trim($_POST['location']);
        $is_ceo = isset($_POST['is_ceo']) ? 1 : 0;
        
        // Handle image update
        $image_path = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = $_FILES['image']['type'];
            
            if (in_array($file_type, $allowed_types)) {
                $upload_dir = 'assets/img/team/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $file_name = 'team_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
                    $image_path = $file_path;
                }
            }
        }

        if ($image_path) {
            // Update with new image
            $stmt = $pdo->prepare("UPDATE team_members SET name=?, role=?, bio=?, location=?, image_path=?, is_ceo=? WHERE id=?");
            $result = $stmt->execute([$name, $role, $bio, $location, $image_path, $is_ceo, $id]);
        } else {
            // Update without changing image
            $stmt = $pdo->prepare("UPDATE team_members SET name=?, role=?, bio=?, location=?, is_ceo=? WHERE id=?");
            $result = $stmt->execute([$name, $role, $bio, $location, $is_ceo, $id]);
        }
        
        if ($result) {
            $_SESSION['flash'] = ['message'=>'Team member updated successfully!','color'=>'#007bff'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to update team member.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- TOGGLE ACTIVE/INACTIVE ----------
    if (isset($_POST['toggle'])) {
        $id = intval($_POST['id']);
        $currentStatus = $_POST['current_status'] === 'active' ? 'inactive' : 'active';

        $stmt = $pdo->prepare("UPDATE team_members SET status=? WHERE id=?");
        if ($stmt->execute([$currentStatus, $id])) {
            $statusText = $currentStatus=='active' ? 'Team member activated!' : 'Team member deactivated!';
            $statusColor = $currentStatus=='active' ? '#28a745' : '#dc3545';
            $_SESSION['flash'] = ['message'=>$statusText,'color'=>$statusColor];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to update status.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
    
    // ---------- DELETE ----------
    if (isset($_POST['delete'])) {
        $id = intval($_POST['id']);
        
        // Get image path first to delete the file
        $stmt = $pdo->prepare("SELECT image_path FROM team_members WHERE id = ?");
        $stmt->execute([$id]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Delete the record
        $stmt = $pdo->prepare("DELETE FROM team_members WHERE id = ?");
        if ($stmt->execute([$id])) {
            // Delete the image file if exists
            if ($member && !empty($member['image_path']) && file_exists($member['image_path'])) {
                unlink($member['image_path']);
            }
            $_SESSION['flash'] = ['message'=>'Team member deleted successfully!','color'=>'#dc3545'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to delete team member.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Team Members ----------------
$teamStmt = $pdo->query("
    SELECT *
    FROM team_members
    ORDER BY is_ceo DESC, name ASC
");
$team_members = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- Add TinyMCE CSS and JS links in the head section -->
<link rel="stylesheet" href="assets/tinymce/skins/ui/oxide/skin.min.css">
<script src="assets/tinymce/tinymce.min.js"></script>

<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Team Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addMemberModal">Add Team Member</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Role</th>
                    <th>Location</th>
                    <th>CEO</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($team_members as $member): ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td>
                      <?php if (!empty($member['image_path'])): ?>
                        <img src="<?= $member['image_path'] ?>" alt="<?= htmlspecialchars($member['name']) ?>" 
                             style="width: 60px; height: 60px; object-fit: cover; border-radius: 50%;">
                      <?php else: ?>
                        <div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                          <span class="text-muted" style="font-size: 12px;">No Image</span>
                        </div>
                      <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($member['name']) ?></td>
                    <td><?= htmlspecialchars($member['role']) ?></td>
                    <td><?= htmlspecialchars($member['location'] ?: 'N/A') ?></td>
                    <td>
                      <?php if ($member['is_ceo']): ?>
                        <span class="badge badge-success">CEO</span>
                      <?php else: ?>
                        <span class="badge badge-secondary">Team</span>
                      <?php endif; ?>
                    </td>
                    <td style="color: <?= $member['status']=='active'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                        <?= ucfirst($member['status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $member['id'] ?>">Edit</button>
                      
                      <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#viewModal<?= $member['id'] ?>">View</button>

                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $member['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $member['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle" class="btn btn-sm <?= $member['status']=='active'?'btn-secondary':'btn-success' ?>">
                          <?= $member['status']=='active'?'Deactivate':'Activate' ?>
                        </button>
                      </form>
                      
                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $member['id'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="delete" class="btn btn-sm btn-danger" 
                                onclick="return confirm('Are you sure you want to delete this team member?')">Delete</button>
                      </form>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Team Member Modal -->
<div class="modal fade" id="addMemberModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add New Team Member</label>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label>Name *</label>
                <input type="text" name="name" class="form-control" placeholder="Enter full name" required>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label>Role/Position *</label>
                <input type="text" name="role" class="form-control" placeholder="e.g., CEO, Developer, Designer" required>
              </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label>Location</label>
                <input type="text" name="location" class="form-control" placeholder="e.g., New York, USA">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label>CEO Status</label>
                <div class="checkbox">
                  <label>
                    <input type="checkbox" name="is_ceo" value="1"> Mark as CEO
                  </label>
                  <small class="text-muted d-block">Only one member should be marked as CEO</small>
                </div>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label>Bio *</label>
            <textarea id="bioAdd" name="bio" class="form-control" rows="8" placeholder="Enter team member bio/description" required></textarea>
          </div>
          
          <div class="form-group">
            <label>Profile Image</label>
            <input type="file" name="image" class="form-control-file" accept="image/*">
            <small class="text-muted">Optional: Upload profile image (JPG, PNG, GIF, WebP)</small>
            <small class="text-muted d-block">Recommended: Square image, 400x400px minimum</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- MODALS MUST BE OUTSIDE THE TABLE/TBODY -->
<?php foreach($team_members as $member): ?>
<!-- View Modal -->
<div class="modal fade" id="viewModal<?= $member['id'] ?>" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4>Team Member Details</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-4">
            <?php if (!empty($member['image_path'])): ?>
              <img src="<?= $member['image_path'] ?>" alt="<?= htmlspecialchars($member['name']) ?>" 
                   class="img-fluid rounded-circle mb-3" style="max-height: 200px; object-fit: cover;">
            <?php else: ?>
              <div class="rounded-circle bg-light d-flex align-items-center justify-content-center mb-3" 
                   style="width: 200px; height: 200px;">
                <span class="text-muted">No Image</span>
              </div>
            <?php endif; ?>
          </div>
          <div class="col-md-8">
            <h4><?= htmlspecialchars($member['name']) ?></h4>
            <p class="lead"><?= htmlspecialchars($member['role']) ?></p>
            
            <?php if ($member['is_ceo']): ?>
              <span class="badge badge-success mb-2">CEO</span>
            <?php endif; ?>
            
            <?php if (!empty($member['location'])): ?>
              <p><strong>Location:</strong> <?= htmlspecialchars($member['location']) ?></p>
            <?php endif; ?>
            
            <p><strong>Bio:</strong></p>
            <div class="border p-3 bg-light">
              <?= nl2br(htmlspecialchars($member['bio'])) ?>
            </div>
            
            <p class="text-muted mt-3">
              <small>Status: <?= ucfirst($member['status']) ?></small><br>
              <small>Created: <?= date('Y-m-d H:i', strtotime($member['created_at'])) ?></small><br>
              <small>Last Updated: <?= date('Y-m-d H:i', strtotime($member['updated_at'])) ?></small>
            </p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal<?= $member['id'] ?>" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <input type="hidden" name="id" value="<?= $member['id'] ?>">

        <div class="modal-header">
          <h4>Edit Team Member</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label>Name *</label>
                <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($member['name']) ?>" required>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label>Role/Position *</label>
                <input type="text" name="role" class="form-control" value="<?= htmlspecialchars($member['role']) ?>" required>
              </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label>Location</label>
                <input type="text" name="location" class="form-control" value="<?= htmlspecialchars($member['location']) ?>" placeholder="e.g., New York, USA">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label>CEO Status</label>
                <div class="checkbox">
                  <label>
                    <input type="checkbox" name="is_ceo" value="1" <?= $member['is_ceo'] ? 'checked' : '' ?>> Mark as CEO
                  </label>
                  <small class="text-muted d-block">Only one member should be marked as CEO</small>
                </div>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label>Bio *</label>
            <textarea id="bioEdit<?= $member['id'] ?>" name="bio" class="form-control tinymce-editor" rows="8" required><?= htmlspecialchars($member['bio']) ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Profile Image</label>
            <?php if (!empty($member['image_path'])): ?>
              <div class="mb-2">
                <img src="<?= $member['image_path'] ?>" alt="Current Image" 
                     style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;" class="img-thumbnail">
                <br>
                <small class="text-muted">Current image</small>
              </div>
            <?php endif; ?>
            <input type="file" name="image" class="form-control-file" accept="image/*">
            <small class="text-muted">Upload new image to replace current one</small>
          </div>
          
          <div class="form-group">
            <label>Status</label>
            <select class="form-control" disabled>
              <option><?= ucfirst($member['status']) ?></option>
            </select>
            <small class="text-muted">Use Activate/Deactivate button to change status</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="update" class="btn btn-outline-primary btn-md">Update</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endforeach; ?>

<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

.img-thumbnail {
  border: 1px solid #ddd;
}

/* Fix modal backdrop */
.modal-backdrop {
  z-index: 1040 !important;
}
.modal {
  z-index: 1050 !important;
}

/* TinyMCE adjustments for modals */
.tox-tinymce {
  border: 1px solid #ddd !important;
  border-radius: 4px !important;
}

/* Profile image styling */
.rounded-circle {
  border-radius: 50% !important;
}
</style>

<script>
// Initialize TinyMCE for modals
function initTinyMCE(selector) {
    if (typeof tinymce !== 'undefined') {
        // Remove existing editor instance if any
        tinymce.remove(selector);
        
        // Initialize new editor
        tinymce.init({
            selector: selector,
            height: 300,
            menubar: false,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
            ],
            toolbar: 'undo redo | formatselect | bold italic backcolor | \
                      alignleft aligncenter alignright alignjustify | \
                      bullist numlist outdent indent | removeformat | help',
            content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });
    } else {
        console.error('TinyMCE not loaded');
    }
}

// Initialize TinyMCE when modals are shown
$(document).ready(function() {
    // Initialize TinyMCE for add modal
    $('#addMemberModal').on('shown.bs.modal', function () {
        initTinyMCE('#bioAdd');
    });
    
    // Initialize TinyMCE for each edit modal
    <?php foreach($team_members as $member): ?>
    $('#editModal<?= $member['id'] ?>').on('shown.bs.modal', function () {
        initTinyMCE('#bioEdit<?= $member['id'] ?>');
    });
    
    // Destroy TinyMCE when modal is hidden
    $('#editModal<?= $member['id'] ?>').on('hidden.bs.modal', function () {
        if (typeof tinymce !== 'undefined') {
            tinymce.remove('#bioEdit<?= $member['id'] ?>');
        }
    });
    <?php endforeach; ?>
    
    // Destroy TinyMCE for add modal when hidden
    $('#addMemberModal').on('hidden.bs.modal', function () {
        if (typeof tinymce !== 'undefined') {
            tinymce.remove('#bioAdd');
        }
    });
});

// Alert when marking as CEO
$(document).ready(function() {
    $('input[name="is_ceo"]').on('change', function() {
        if ($(this).is(':checked')) {
            if (!confirm('Are you sure you want to mark this member as CEO? Only one member should be CEO.')) {
                $(this).prop('checked', false);
            }
        }
    });
});
</script>

<?php include('includes/footer.php'); ?>

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload = function() {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
    toast.innerText = '<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>