<?php
header('Content-Type: application/json');
ini_set('display_errors', '0');
error_reporting(E_ALL);
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../config/db.php';
function respond_json($data, $status = 200){ http_response_code($status); echo json_encode($data); exit; }
function payload(){ $raw=file_get_contents('php://input'); if($raw){ $d=json_decode($raw,true); if(is_array($d)) return $d; } return $_POST; }
function session_family_id(){ if(!empty($_SESSION['family_id'])) return (int)$_SESSION['family_id']; if(!empty($_SESSION['session']['family_id'])) return (int)$_SESSION['session']['family_id']; if(!empty($_SESSION['family']['id'])) return (int)$_SESSION['family']['id']; return 0; }
function family_from_client($pdo,$clientId){ if($clientId<=0) return 0; $s=$pdo->prepare('SELECT family_id FROM clients WHERE id=? LIMIT 1'); $s->execute([$clientId]); $r=$s->fetch(PDO::FETCH_ASSOC); return $r?(int)$r['family_id']:0; }
function ensure_tasks($pdo){ $pdo->exec("CREATE TABLE IF NOT EXISTS tasks (
 id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
 family_id BIGINT UNSIGNED NOT NULL,
 client_id BIGINT UNSIGNED NOT NULL,
 entry_date DATE NULL,
 task_time VARCHAR(10) DEFAULT '',
 task_type VARCHAR(100) DEFAULT '',
 details TEXT NULL,
 completed TINYINT(1) NOT NULL DEFAULT 0,
 created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
 updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 KEY idx_family_client_date (family_id, client_id, entry_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); }
try {
 ensure_tasks($pdo);
 $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
 if($method==='GET'){
   $clientId = isset($_GET['client_id'])?(int)$_GET['client_id']:0;
   $familyId = !empty($_GET['family_id'])?(int)$_GET['family_id']:session_family_id();
   if($familyId<=0 && $clientId>0) $familyId=family_from_client($pdo,$clientId);
   if($familyId<=0) respond_json(['success'=>false,'message'=>'Family session required.'],403);
   if($clientId<=0) respond_json(['success'=>false,'message'=>'client_id is required.'],422);
   $stmt=$pdo->prepare('SELECT id, client_id, entry_date, task_time, task_type, details, completed, created_at, updated_at FROM tasks WHERE family_id=? AND client_id=? ORDER BY entry_date DESC, id DESC');
   $stmt->execute([$familyId,$clientId]);
   respond_json(['success'=>true,'tasks'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
 }
 $data = payload();
 $action = isset($data['action'])?(string)$data['action']:'save';
 $clientId = isset($data['client_id'])?(int)$data['client_id']:0;
 $familyId = !empty($data['family_id'])?(int)$data['family_id']:session_family_id();
 if($familyId<=0 && $clientId>0) $familyId=family_from_client($pdo,$clientId);
 if($familyId<=0) respond_json(['success'=>false,'message'=>'Family session required.'],403);
 if($action==='delete'){
   $id = isset($data['id'])?(int)$data['id']:0;
   if($id<=0) respond_json(['success'=>false,'message'=>'Task id is required.'],422);
   $stmt=$pdo->prepare('DELETE FROM tasks WHERE id=? AND family_id=?'); $stmt->execute([$id,$familyId]);
   respond_json(['success'=>true,'message'=>'Task deleted.']);
 }
 if($clientId<=0) respond_json(['success'=>false,'message'=>'client_id is required.'],422);
 $entryDate = isset($data['entry_date'])?(string)$data['entry_date']:null;
 $taskTime = isset($data['task_time'])?(string)$data['task_time']:(isset($data['time'])?(string)$data['time']:'');
 $taskType = isset($data['task_type'])?(string)$data['task_type']:(isset($data['type'])?(string)$data['type']:'');
 $details = isset($data['details'])?(string)$data['details']:'';
 $completed = !empty($data['completed'])?1:0;
 $id = isset($data['id'])?(int)$data['id']:0;
 if($id>0){ $stmt=$pdo->prepare('UPDATE tasks SET entry_date=?, task_time=?, task_type=?, details=?, completed=?, updated_at=NOW() WHERE id=? AND family_id=?'); $stmt->execute([$entryDate,$taskTime,$taskType,$details,$completed,$id,$familyId]); }
 else { $stmt=$pdo->prepare('INSERT INTO tasks (family_id, client_id, entry_date, task_time, task_type, details, completed, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())'); $stmt->execute([$familyId,$clientId,$entryDate,$taskTime,$taskType,$details,$completed]); $id=(int)$pdo->lastInsertId(); }
 respond_json(['success'=>true,'message'=>'Task saved.','task'=>['id'=>$id,'client_id'=>$clientId,'entry_date'=>$entryDate,'task_time'=>$taskTime,'task_type'=>$taskType,'details'=>$details,'completed'=>$completed===1]]);
} catch (Throwable $e) {
 error_log('tasks.php error: '.$e->getMessage());
 respond_json(['success'=>false,'message'=>'server error','error'=>$e->getMessage()],500);
}
