<?php 
 // Include main file
include_once('../libs/main.php');
// $zip = new ZipArchive;
// print_r("<pre>");
// print_r($zip);
// exit;
 
$dependantObj = new dependant();
$dependantObj->resultAs ='array';
$fields =array('DISTINCT dependant_city_zipcode as cityZipcode');
$where ="dependant_city_zipcode!='' ";
// $limit = array('start'=>0,'record'=>4);
// $arg =array('fields'=>$fields,'where'=>$where,'limit'=>$limit);
$arg =array('fields'=>$fields,'where'=>$where);
$allzipcode =$dependantObj->getAllRecords($arg);
if($allzipcode && count($allzipcode)>0){
    $zipname = 'patient.zip';
    $zipObj = new ZipArchive;
    $zipObj->open($zipname, ZipArchive::CREATE);
    
    foreach ($allzipcode as $key => $zip) {
        $dependantObj = new dependant();
        $delimiter = ","; 
        $filename =  $zip['cityZipcode'].".csv";      
        // Create a file pointer 
        $f = fopen($filename, 'w'); 
        $fields =array('dependant_fname as fname','dependant_lname as lname','dependant_email_address as email','dependant_phone as phone','dependant_dob as dob','dependant_gender as gender','dependant_insurance_name as insurance','dependant_address1 as address1','dependant_address2 as address2','dependant_city as city','dependant_state as state','dependant_zipcode as zipcode');
        $where = array('dependant_city_zipcode='=>$zip['cityZipcode']);
        $dArg =array('fields'=>$fields,'where'=>$where);
        $allDependant =$dependantObj->getAllRecords($dArg);
        // print_r("<pre>");
        // print_r(count($allDependant));
        // continue;
        if($allDependant && count($allDependant)>0){
            // Set column headers 
            $fields = array('FIRST NAME', 'LAST NAME', 'EMAIL','PHONE','DOB' ,'GENDER', 'INSURANCE','ADDRESS 1', 'ADDRESS 2', 'CITY','STATE','ZIPCODE'); 
            fputcsv($f, $fields, $delimiter); 
            foreach ($allDependant as $key => $d) {
                $lineData = array(w::d($d->fname), w::d($d->lname),w::d($d->email),w::d($d->phone),w::d($d->dob),$d->gender,$d->insurance,$d->address1,$d->address2,$d->city,$d->state,$d->zipcode); 
                fputcsv($f, $lineData, $delimiter);         
            }
            // // Move back to beginning of file 
            // fseek($f, 0); 

        }
        // // Set headers to download file rather than displayed 
        // header('Content-Type: text/csv'); 
        // header('Content-Disposition: attachment; filename="' . $filename . '";'); 
         
        // //output all remaining data on a file pointer 
        // fpassthru($f); 
        // fclose($f); 
        $zipObj->addFile($filename);
        

    }
    
    $zipObj->close(); 
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));
    readfile($zipname);
} 
exit; 
