<?php
// ============================================================
// HHP Staff & Site Manager — PHP API Backend
// ============================================================
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') { http_response_code(204); exit; }

// ── Database config ───────────────────────────────────────────
require_once __DIR__ . '/config.php';
requireManagerLogin();

// ── Upload directory ──────────────────────────────────────────
// Upload and base URL constants are provided by config.php.
if (!defined('BASE_URL')) define('BASE_URL', 'https://workspace.hammerheadstaffing.com');

// ── Load mailer (non-fatal — email failures never break the API) ──
$_mailerLoaded = false;
if (file_exists(__DIR__ . '/mailer.php')) {
    try { require_once __DIR__ . '/mailer.php'; $_mailerLoaded = true; }
    catch (Throwable $e) { error_log('Mailer load error: ' . $e->getMessage()); }
}

function ok($data = null): void {
    echo json_encode(['success' => true, 'data' => $data]); exit;
}
function err(string $msg, int $code = 400): void {
    http_response_code($code);
    echo json_encode(['success' => false, 'message' => $msg]); exit;
}

set_exception_handler(function (Throwable $e): void {
    error_log('API fatal: ' . $e->getMessage());
    if (!headers_sent()) { header('Content-Type: application/json'); http_response_code(500); }
    echo json_encode(['success'=>false,'message'=>'Server error: '.$e->getMessage()]);
    exit;
});

$action = $_REQUEST['action'] ?? '';

// ── Route ─────────────────────────────────────────────────────
switch ($action) {

// ── Seed / import employees, managers, sites from CSV upload ──
// (These replace the Google Sheet read in GAS)

case 'getCustomData': {
    $db = db();
    $employees = $db->query("SELECT name,phone,phone2,ext FROM employees ORDER BY name")->fetchAll();
    $managers  = $db->query("SELECT name,dept,email FROM managers ORDER BY name")->fetchAll();
    $sites     = array_column($db->query("SELECT name FROM sites ORDER BY name")->fetchAll(), 'name');
    ok(['employees'=>$employees,'managers'=>$managers,'sites'=>$sites]);
}

case 'getTasks': {
    $db = db();
    $rows = $db->query("SELECT * FROM tasks ORDER BY created_at DESC")->fetchAll();
    $tasks = [];
    foreach ($rows as $r) {
        // Decode JSON fields
        $r['history']     = $r['history']     ?: '[]';
        $r['attachments'] = $r['attachments'] ?: '[]';
        $r['links']       = $r['links']       ?: '[]';
        unset($r['created_at'], $r['updated_at']);
        $tasks[] = $r;
    }
    ok($tasks);
}

case 'createTask': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $t = $input['task'] ?? $input;
    if (empty($t['id'])) err('Missing task id');
    $db = db();
    $cols = ['id','sheetId','type','subj','empId','concern','otherProcessType',
             'findings','date','mgrBy','mgrByEmail','mgrTo','mgrToEmail',
             'currentlyAssignedTo','startDate','endDate','followupRequired',
             'assignedSite','assignedDesc','followUp','followUpDate','followUpStartDate',
             'nextFollowUpDue','transferTo','transferEmail','transferStatus',
             'transferFollowUp','status','created','createdTasksFiles',
             'transferTasksFiles','history','attachments','links'];
    $ph  = implode(',', array_map(fn($c) => ":$c", $cols));
    $fld = implode(',', array_map(fn($c) => "`$c`", $cols));
    $stmt = $db->prepare("INSERT INTO tasks ($fld) VALUES ($ph)");
    $bind = [];
    foreach ($cols as $c) {
        $v = $t[$c] ?? '';
        if (is_array($v)) $v = json_encode($v);
        $bind[$c] = (string)$v;
    }
    $stmt->execute($bind);

    // ── Email notification to assignee ────────────────────────
    global $_mailerLoaded;
    if ($_mailerLoaded && function_exists('mailTaskAssigned')) {
        try { mailTaskAssigned($t); }
        catch (Throwable $e) { error_log('mailTaskAssigned: ' . $e->getMessage()); }
    }

    // ── Email notification to logged-in manager ──────────────
    if ($_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Task Created',
                $t,
                "Created new task and assigned to " . ($t['mgrTo'] ?? 'N/A')
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction createTask error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'updateTaskStatus': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id     = $input['taskId']  ?? ''; $status = $input['status'] ?? '';
    if (!$id) err('Missing taskId');
    $db = db();
    
    // Fetch task details for email notification
    $stmt = $db->prepare("SELECT * FROM tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $task = $stmt->fetch();

    $db->prepare("UPDATE tasks SET `status`=?, updated_at=NOW() WHERE id=?")->execute([$status,$id]);

    global $_mailerLoaded;
    if ($task && $_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Task Status Updated',
                $task,
                "Updated status from '" . ($task['status'] ?? 'N/A') . "' to '{$status}'."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction updateTaskStatus error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'updateTaskTransfer': {
    $input  = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id     = $input['taskId'] ?? ''; $data = $input['data'] ?? [];
    if (!$id) err('Missing taskId');
    $allowed = ['transferTo','transferEmail','transferStatus','followUp','followUpDate',
                'followUpStartDate','nextFollowUpDue','transferFollowUp','currentlyAssignedTo',
                'followupRequired','transferTasksFiles','history','attachments',
                'startDate','endDate','otherProcessType','status'];
    $set = []; $bind = [];
    foreach ($allowed as $f) {
        if (array_key_exists($f, $data)) {
            $v = $data[$f]; if (is_array($v)) $v = json_encode($v);
            $set[]  = "`$f`=?"; $bind[] = (string)$v;
        }
    }
    if (empty($set)) err('No fields to update');
    $bind[] = $id;
    db()->prepare("UPDATE tasks SET ".implode(',',$set).", updated_at=NOW() WHERE id=?")->execute($bind);

    // ── Email notification to new assignee ────────────────────
    global $_mailerLoaded;
    if ($_mailerLoaded && function_exists('mailTaskTransferred')) {
        try {
            // Re-read the full updated task row for the email
            $row = db()->prepare("SELECT * FROM tasks WHERE id=? LIMIT 1");
            $row->execute([$id]);
            $updatedTask = $row->fetch();
            if ($updatedTask) {
                $prevAssignee = $data['_prevAssignee'] ?? ''; // sent by frontend in data
                $note         = $data['_note']         ?? '';
                mailTaskTransferred($updatedTask, $prevAssignee, $note);
                
                if (function_exists('mailManagerAction')) {
                    mailManagerAction(
                        $_SESSION['manager_email'],
                        $_SESSION['manager_name'],
                        'Task Transferred',
                        $updatedTask,
                        "Transferred task to " . ($updatedTask['transferTo'] ?? 'N/A') . " (" . ($updatedTask['transferEmail'] ?? 'N/A') . ")."
                    );
                }
            }
        } catch (Throwable $e) { error_log('mailTaskTransferred / mailManagerAction transfer: ' . $e->getMessage()); }
    }

    ok();
}

case 'updateTaskHistory': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id    = $input['taskId'] ?? ''; $hist = $input['historyJson'] ?? '[]';
    if (!$id) err('Missing taskId');
    $db = db();
    
    // Fetch task details for email notification
    $stmt = $db->prepare("SELECT * FROM tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $task = $stmt->fetch();

    $db->prepare("UPDATE tasks SET `history`=?, updated_at=NOW() WHERE id=?")->execute([$hist,$id]);

    global $_mailerLoaded;
    if ($task && $_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Task History Updated',
                $task,
                "Updated task history / notes."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction updateTaskHistory error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'updateTaskField': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id    = $input['taskId']    ?? '';
    $field = $input['fieldName'] ?? '';
    $value = $input['value']     ?? '';
    if (!$id || !$field) err('Missing params');
    $allowed = ['startDate','endDate','nextFollowUpDue','followUpDate','followUpStartDate',
                'status','followupRequired','currentlyAssignedTo'];
    if (!in_array($field, $allowed)) err('Field not allowed');
    $db = db();

    // Fetch task details for email notification
    $stmt = $db->prepare("SELECT * FROM tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $task = $stmt->fetch();

    $db->prepare("UPDATE tasks SET `$field`=?, updated_at=NOW() WHERE id=?")->execute([(string)$value,$id]);

    global $_mailerLoaded;
    if ($task && $_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Task Field Updated',
                $task,
                "Updated field '{$field}' from '" . ($task[$field] ?? 'N/A') . "' to '{$value}'."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction updateTaskField error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'deleteTask': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id = $input['taskId'] ?? '';
    if (!$id) err('Missing taskId');
    $db = db();

    // Fetch task details BEFORE deleting for email notification
    $stmt = $db->prepare("SELECT * FROM tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $task = $stmt->fetch();

    $db->prepare("DELETE FROM tasks WHERE id=?")->execute([$id]);
    // Also delete any uploaded files
    $files = $db->prepare("SELECT file_path FROM task_files WHERE task_id=?");
    $files->execute([$id]);
    foreach ($files->fetchAll() as $f) {
        @unlink(UPLOAD_DIR . basename($f['file_path']));
    }
    $db->prepare("DELETE FROM task_files WHERE task_id=?")->execute([$id]);

    global $_mailerLoaded;
    if ($task && $_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Task Deleted',
                $task,
                "Permanently deleted task #{$id}."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction deleteTask error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'uploadAttachments': {
    // Accepts multipart/form-data with files[] + taskId + fileType
    $taskId   = $_POST['taskId']   ?? '';
    $fileType = $_POST['fileType'] ?? 'created'; // 'created' or 'transfer'
    if (!$taskId) err('Missing taskId');
    if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
    $result = [];
    $files  = $_FILES['files'] ?? [];
    if (empty($files['name'])) err('No files received');
    $count = is_array($files['name']) ? count($files['name']) : 1;
    for ($i = 0; $i < $count; $i++) {
        $name  = is_array($files['name'])  ? $files['name'][$i]     : $files['name'];
        $tmp   = is_array($files['tmp_name'])? $files['tmp_name'][$i]: $files['tmp_name'];
        $mime  = is_array($files['type'])  ? $files['type'][$i]     : $files['type'];
        $err2  = is_array($files['error']) ? $files['error'][$i]    : $files['error'];
        if ($err2 !== UPLOAD_ERR_OK) continue;
        $ext      = pathinfo($name, PATHINFO_EXTENSION);
        $safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $name);
        $fname    = uniqid('hhp_', true) . '_' . $safeName;
        $dest     = UPLOAD_DIR . $fname;
        if (!move_uploaded_file($tmp, $dest)) continue;
        $isImg  = strpos($mime, 'image/') === 0;
        $url    = UPLOAD_URL . $fname;
        $prevUrl = $isImg ? $url : '';
        // Save to DB
        db()->prepare("INSERT INTO task_files (task_id,file_type,file_name,file_path,mime_type,is_image)
                       VALUES (?,?,?,?,?,?)")
            ->execute([$taskId, $fileType, $name, $fname, $mime, $isImg ? 1 : 0]);
        $result[] = [
            'name'       => $name,
            'url'        => $url,
            'previewUrl' => $prevUrl,
            'mimeType'   => $mime,
            'isImage'    => $isImg,
        ];
    }
    ok($result);
}

case 'addEmployee': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $emp   = $input['emp'] ?? $input;
    if (empty($emp['name'])) err('Name required');
    db()->prepare("INSERT INTO employees (name,phone,phone2,ext,source) VALUES (?,?,?,?,'custom')")
        ->execute([$emp['name'],$emp['phone']??'',$emp['phone2']??'',$emp['ext']??'']);

    global $_mailerLoaded;
    if ($_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Employee Added',
                ['id' => 'N/A', 'subj' => $emp['name']],
                "Added new employee '{$emp['name']}' to the database."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction addEmployee error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'addSite': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $name  = $input['name'] ?? $input['site'] ?? '';
    if (!$name) err('Site name required');
    db()->prepare("INSERT INTO sites (name,source) VALUES (?,'custom')")->execute([$name]);

    global $_mailerLoaded;
    if ($_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Site Added',
                ['id' => 'N/A', 'subj' => $name],
                "Added new site '{$name}' to the database."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction addSite error: ' . $e->getMessage());
        }
    }

    ok();
}

case 'addManager': {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $mgr   = $input['mgr'] ?? $input;
    if (empty($mgr['name'])) err('Name required');
    db()->prepare("INSERT INTO managers (name,dept,email,source) VALUES (?,?,?,'custom')")
        ->execute([$mgr['name'],$mgr['dept']??'',$mgr['email']??'']);

    global $_mailerLoaded;
    if ($_mailerLoaded && function_exists('mailManagerAction')) {
        try {
            mailManagerAction(
                $_SESSION['manager_email'],
                $_SESSION['manager_name'],
                'Manager Added',
                ['id' => 'N/A', 'subj' => $mgr['name']],
                "Added new manager '{$mgr['name']}' (Email: " . ($mgr['email'] ?? 'N/A') . ", Dept: " . ($mgr['dept'] ?? 'N/A') . ")."
            );
        } catch (Throwable $e) {
            error_log('mailManagerAction addManager error: ' . $e->getMessage());
        }
    }

    ok();
}

// ── Bulk import (optional: POST CSV data) ─────────────────────
case 'importEmployees': {
    $input = json_decode(file_get_contents('php://input'), true);
    $db = db(); $db->beginTransaction();
    foreach ($input['employees'] ?? [] as $e) {
        $db->prepare("INSERT IGNORE INTO employees (name,phone,phone2,ext,source) VALUES (?,?,?,?,'import')")
           ->execute([$e['name']??'',$e['phone']??'',$e['phone2']??'',$e['ext']??'']);
    }
    $db->commit(); ok(['imported'=>count($input['employees']??[])]);
}
case 'importManagers': {
    $input = json_decode(file_get_contents('php://input'), true);
    $db = db(); $db->beginTransaction();
    foreach ($input['managers'] ?? [] as $m) {
        $db->prepare("INSERT IGNORE INTO managers (name,dept,email,source) VALUES (?,?,?,'import')")
           ->execute([$m['name']??'',$m['dept']??'',$m['email']??'']);
    }
    $db->commit(); ok(['imported'=>count($input['managers']??[])]);
}
case 'importSites': {
    $input = json_decode(file_get_contents('php://input'), true);
    $db = db(); $db->beginTransaction();
    foreach ($input['sites'] ?? [] as $s) {
        $db->prepare("INSERT IGNORE INTO sites (name,source) VALUES (?,'import')")->execute([$s]);
    }
    $db->commit(); ok(['imported'=>count($input['sites']??[])]);
}

default:
    err('Unknown action: '.$action, 404);
}
